Copy part of an array with slice()
suggest changeTo copy part of an array:
arr.slice(begin, end)arr.slice(begin)
It returns a new array filled with items from arr.
begin is the 0-based index of the first item.
end is the 0-based index of the first item not copied. slice(0, 2) therefore copies indexes 0 and 1.
If only begin is given, slice copies through the end of the array.
If end is negative it becomes end = arr.length + end. -1 leaves off the last element, -2 the last two, and so on.
If end is ≤ begin, slice returns an empty array.
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let newArr = arr.slice(0, 2);
console.log("slice(0,2) :", newArr)
newArr = arr.slice(8);
console.log("slice(8) :", newArr)
newArr = arr.slice(5, -1);
console.log("slice(5, -1):", newArr)
newArr = arr.slice(6, -2);
console.log("slice(6, -2):", newArr)
newArr = arr.slice(3, 3)
console.log("slice(3, 3) :", newArr)
newArr = arr.slice(4, 1)
console.log("slice(4, 1) :", newArr)
slice(0,2) : [ 0, 1 ]
slice(8) : [ 8, 9 ]
slice(5, -1): [ 5, 6, 7, 8 ]
slice(6, -2): [ 6, 7 ]
slice(3, 3) : []
slice(4, 1) : []
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents