Javascript Array slice()

Introduction

Javascript array slice() method returns a sub array.

It returns a new array containing the extracted elements.

arr.slice([begin[, end]])
Parameter
Optional
Meaning
begin




Optional




Zero-based index to begin extraction.
Default to 0.
A negative index indicates an offset from the end of the sequence.
slice(-2) extracts the last two elements in the sequence.
If begin is greater than the array length, an empty array is returned.
end






Optional






Zero-based index to end extraction.
slice extracts up to but not including end.
slice(1,4) extracts elements indexed 1, 2, and 3.
A negative index indicates an offset from the end of the sequence.
slice(2,-1) extracts the third element through the second-to-last element.
If end is omitted, slice() extracts through the end of arr.length.
If end is greater than the arr.length, slice() uses arr.length.

slice() does not alter the original array.

Extract the third and fourth elements, using negative numbers.

var languages = ["CSS", "HTML", "SQL", "Java", "Javascript"];
var myBest = languages.slice(-3, -1);
console.log(myBest);//from  w  w  w  . j a  v  a2  s .co m

Return a portion of an existing array

let languages = ['CSS', 'Java', 'Javascript', 'HTML', 'C++']
let r = languages.slice(1, 3)
console.log(r);

More examples

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

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



PreviousNext

Related