JS: Array.prototype.slice (extract)
The “slice” function lets you extract a sub-array from a array.
xArray.slice()-
Return a copy of array.
console.log([1, 2, 3].slice()); // [ 1, 2, 3 ] // original not changed const xx = [1, 2, 3]; const yy = xx.slice(); console.log((xx === yy) === false); // true xArray.slice(start)-
Start at index start.
Index can be negative. Means count from right.
// take starting at index 1 to end console.log([0, 1, 2, 3].slice(1)); // [ 1, 2, 3 ] // take last 2 items console.log([0, 1, 2, 3].slice(-2)); // [ 2, 3 ] xArray.slice(start, end)-
End at end but does not include end.
console.log([0, 1, 2, 3, 4, 5, 6].slice(1, 2)); // [ 1 ]
Edge Cases
out of bound end index
// out of bound end index just get the max index console.log([0, 1, 2].slice(1, 9)); // [ 1, 2 ]
Sparse array
Does not convert Sparse Array to dense array.
// slice does not convert sparse array to dense array console.log(Array(4)); // [ <4 empty items> ] console.log(Array(4).slice()); // [ <4 empty items> ]
Array-like object
Can be used on Array-Like Object to get a copy of real array.
// slice can convert array-like object to array const xx = { "0": "a", "1": "b", "length": 2 }; const yy = Reflect.apply(Array.prototype.slice, xx, []); console.log(JSON.stringify(xx) === `{"0":"a","1":"b","length":2}`); console.log(JSON.stringify(yy) === `["a","b"]`);