1

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

Luca Kiebel
  • 9,200
  • 6
  • 29
  • 43
David
  • 3,817
  • 8
  • 26
  • 54
  • `arr.splice(1500,arr.length)` – kind user Jul 21 '17 at 08:58
  • Possible duplicate of [How do I remove a particular element from an array in JavaScript?](https://stackoverflow.com/questions/5767325/how-do-i-remove-a-particular-element-from-an-array-in-javascript) – Sudipta Mondal Jul 21 '17 at 09:00
  • splice second argument is the number of items to delete. It's not a range. Omit second parameter to pick from start index (first argument) to end. – Kev Jul 21 '17 at 09:01

4 Answers4

4

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(', '))
Yury Tarabanko
  • 42,049
  • 9
  • 81
  • 96
2

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).

Alberto Trindade Tavares
  • 9,248
  • 5
  • 33
  • 45
0

splice will remove the items.

arr.splice(1500, arr.length)

Ivan Mladenov
  • 1,635
  • 9
  • 15
0

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)
Luong.Khuc
  • 26
  • 3