How to slice a Javascript array

Description

slice() returns the sub-array. The slice() method may accept one or two arguments:

  • the starting
  • stopping positions.

slice(startingPoint) returns sub-array between startingPoint and the end of the array.

slice(startingPoint,endPosition) returns sub-array between the startingPosition and endPosition, not including the item in the end position.

slice() does not affect the original array in any way.

Example


var colors = ["A", "B", "C", "D", "E"]; 
var colors2 = colors.slice(1); 
var colors3 = colors.slice(1,4); 
console.log(colors2); //B,C,D,E
console.log(colors3); //B,C,D
/*from  w  w w  .ja v a2 s  . c  o m*/

The code above generates the following result.

slice negative value

If either the start or end position of slice() is a negative number, then the number is subtracted from the length of the array.

For the array in the following code, arrayWithFiveItem.slice(-2, -1) is the same as arrayWithFiveItem.slice(3, 4).


var colors = ["A", "B", "C", "D", "E"]; 
var colors2 = colors.slice(-2,-1); 
var colors3 = colors.slice(3,4); 
/*  ww w . j  a v  a2s .c  o m*/
console.log(colors2); //D
console.log(colors3); //D
       

If the end position is smaller than the start, then an empty array is returned.

The code above generates the following result.





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window