JS: Array.prototype.slice

By Xah Lee. Date: . Last updated: .

The โ€œsliceโ€ function lets you extract a sub-array from a array.

xArray.slice()

Return a copy of array.

const xx = [1, 2, 3];
const yy = xx.slice();

console.log(JSON.stringify(yy) === "[1,2,3]");
// true

console.log((xx === yy) === false);
// true
// 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"]`);
// slice does not convert sparse array to dense array

console.log(Array(4));
// [ <4 empty items> ]

console.log(Array(4).slice());
// [ <4 empty items> ]
xArray.slice(start)

Start at index start.

// take a subarray, starting with index 1

const xx = ["x0", "x1", "x7"];
const yy = xx.slice(1);

console.log(JSON.stringify(xx) === `["x0","x1","x7"]`);
console.log(JSON.stringify(yy) === `["x1","x7"]`);
xArray.slice(start, end)

End at end but does not include end.

// extract a subarray, from index 1 to 2

const xx = ["x0", "x1", "x2", "x3"];
const yy = xx.slice(1, 2);

console.log(JSON.stringify(xx) === `["x0","x1","x2","x3"]`);
console.log(JSON.stringify(yy) === `["x1"]`);

JavaScript. Add or Remove Subarray