slice
and splice
are common methods to get a sub-array of a given array.array.slice(startingIndex, endingIndex);array.splice(startingIndex, length, ...items);
slice
and splice
are the ending index and the number of sub items, respectively.splice
method, it's possible to keep the items not to be removed from the original array by passing them to the last parameters.splice
changes the original array, while slice
doesn't.const array = [1, 2, 3, 4, 5];const sub = array.splice(2, 3);// The original array is modifiedarray; // [1, 2]sub; // [3, 4, 5]
slice
:const array = [1, 2, 3, 4, 5];const sub = array.slice(2, 3);// The original array isn't modifiedarray; // [1, 2, 3, 4, 5]sub; // [3]
const clone = (arr) => arr.slice(0);