arrays - javascript - typescript remove item from array of objects - How can I remove a specific item from an array?

javascript multidimensional array / javascript

I have an array of numbers and I'm using the .push() method to add elements to it.

I'm looking for the equivalent of something like:

array.remove(number);

Melanie



Answer #1

There is no need to use indexOf or splice. However, it performs better if you only want to remove one occurrence of an element.

Find and move (move):

function move(arr, val) {
  var j = 0;
  for (var i = 0, l = arr.length; i < l; i++) {
    if (arr[i] !== val) {
      arr[j++] = arr[i];
    }
  }
  arr.length = j;
}
function indexof(arr, val) {
  var i;
  while ((i = arr.indexOf(val)) != -1) {
    arr.splice(i, 1);
  }
}
function splice(arr, val) {
  for (var i = arr.length; i--;) {
    if (arr[i] === val) {
      arr.splice(i, 1);
    }
  }
}

indexof is approximately 10x slower than move. Even if improved by removing the call to indexOf in splice it performs much worse than move.

indexof is approximately 10x slower than move. Even if improved by removing the call to indexOf in splice it performs much worse than move.

Remove all occurrences:
    move 0.0048 ms
    indexof 0.0463 ms
    splice 0.0359 ms

Remove first occurrence:
    move_one 0.0041 ms
    indexof_one 0.0021 ms