Javascript - Array to Sub Array


slice() method returns a sub array.

The slice() method may accept one or two arguments: the starting and stopping positions of the items to return.

If only one argument is present, the method returns all items between that position and the end of the array.

If there are two arguments, the method returns all items between the start position and the end position, not including the item in the end position.

This operation does not affect the original array.


var colors = ["red", "green", "blue", "yellow", "purple"];
var colors2 = colors.slice(1);
var colors3 = colors.slice(1,4);

console.log(colors2);   //green,blue,yellow,purple
console.log(colors3);   //green,blue,yellow


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

For example, calling slice(-2, -1) on an array with five items is the same as calling slice(3, 4).

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