David
David

Reputation: 4291

How to delete items from range in array

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

Answers (4)

Luong.Khuc
Luong.Khuc

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

Ivan Mladenov
Ivan Mladenov

Reputation: 1847

splice will remove the items.

arr.splice(1500, arr.length)

Upvotes: 0

Alberto Trindade Tavares
Alberto Trindade Tavares

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

Yury Tarabanko
Yury Tarabanko

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

Related Questions