Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove element from array (splice)

Basic question on .splice() method, and how best to remove an element from an array.

I want to remove an item from an array with .splice() but when I do, I want to have the original array minus the removed element returned. .splice() returns the removed element instead.

var arr = [1, 2, 3, 4, 5, 6, 7]
var newArr = arr.splice(3, 1)

console.log(newArr) // [4]

// whereas I want [1, 2, 3, 5, 6, 7]

What's the best, and most eloquent way to do this?

like image 700
Paulos3000 Avatar asked Sep 29 '26 02:09

Paulos3000


1 Answers

Using the spread operator, you can do:

var arr = [1,2,3,4,5,6],
    indexToRemove = 3,
    newArr = [
      ...arr.slice(0,indexToRemove),
      ...arr.slice(indexToRemove+1)
    ]

Or if you want to use ES5, it can look something like:

var arr = [1,2,3,4,5,6],
    indexToRemove = 3,
    newArr = [].concat(arr.slice(0,indexToRemove)).concat(arr.slice(indexToRemove+1))
like image 136
Tim Roberts Avatar answered Sep 30 '26 17:09

Tim Roberts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!