JS: Array.prototype.slice

By Xah Lee. Date: . Last updated: .

The “slice” function lets you extract a sub-array from a array.

start and end can be negative. When negative, count begin from last element.

Original array is not modified.

// take a sub list, starting with index 1

const r1 = [3,4,2];
const r2 = r1.slice(1);

console.log (r1); // [3,4,2]
console.log (r2); // [4,2]
// extract a sub array, from index 1 to 2 (excludes element at index 2)

const r1 = ["a","b","c","d"];
const r2 = r1.slice(1,2);

console.log (r1); // ["a","b","c","d"]
console.log (r2); // ["b"]
// Array.prototype.slice can be used on array-like object to convert it to array

const r1 = {"0":"a", "1":"b", "length":2};
const r2 = Array.prototype.slice.call(r1,0,3);

console.log (r1); // { '0': 'a', '1': 'b', length: 2 }
console.log (r2); // [ 'a', 'b' ]

[see JS: Array-Like Object to Array]

JS Array

  1. Understand JS Array
  2. Create Array
  3. Sparse Array
  4. Array-Like Object
  5. Array How-To

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials