Reputation: 4291
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
Upvotes: 1
Views: 71
Reputation: 26
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)
Upvotes: 0
Reputation: 10396
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).
Upvotes: 2
Reputation: 45106
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(', '))
Upvotes: 4