I have 3800 items in array. I want to remove all the items after the 1500th. How can I accomplish that?
I tried using this
arr.slice(1500,arr.length)
but it didn't work
I have 3800 items in array. I want to remove all the items after the 1500th. How can I accomplish that?
I tried using this
arr.slice(1500,arr.length)
but it didn't work
slice
creates new array. You need splice
to mutate initial array.
But a simpler way would be to set arr.length = 1500
const arr = new Array(15).fill(1);
console.log(arr.join(', '))
arr.length = 10
console.log(arr.join(', '))
You either use slice
assigning the result to the variable or use splice
:
arr = arr.slice(1500,arr.length)
or
arr.splice(1500,arr.length)
The first one is "more functional", as it does not mutate the variable (you could assign the result to a different variable).
slice
does not change the array which invokes it. You need to clone an arr or assign it selfs
arr = arr.slice(1500, arr.length)