Paulos3000 Paulos3000 - 2 months ago 9
Javascript Question

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?

Answer

.splice mutates the array in place and returns the removed elements. So unless you actually need a function that returns the array itself, just access arr:

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

You can create a wrapper function that performs the splice and returns the array:

function remove(arr, index) {
  arr.splice(index, 1)
  return arr;
}

var newArr = remove(arr, 3);
// Note: `newArr` is not a new array, it has the same value as `arr`

If you want to create a new array, without mutating the original array, you could use .filter:

var newArr = arr.filter(function(element, index) {
  return index !== 3;
}); // [1, 2, 3, 5, 6, 7]
arr; // [1, 2, 3, 4, 5, 6, 7]
Comments