javascript – How to remove a specific element from an array?

Question:

I have an array: [1,2,3,4,5] and I want to remove a particular item.

I have achieved this, but I suppose there are other simpler ways in javascript to achieve it.

function eliminar(array, elemento) {
  var resultado = []
  for (var i = 0; i < array.length; i++) {
    if (array[i] !== elemento) {
      resultado.push(array[i]);
    }
  }
  return resultado;
}

var array = [1,2,3,4,5];

array = eliminar(array, 3);

console.log( array );

What ways does the language provide to do this?

Answer:

There are several ways to remove elements in javascript.

Array.prototype.splice

To use this method, you must know the index of the element to remove.

 var arreglo = [1,2,3,4,5]; var indice = arreglo.indexOf(3); // obtenemos el indice arreglo.splice(indice, 1); // 1 es la cantidad de elemento a eliminar console.log( arreglo );

Array.prototype.filter

This method was introduced in EcmaScript 5, using filter

EcmaScript 5 version:

 var arreglo = [1,2,3,4,5]; arreglo = arreglo.filter(function(i) { return i !== 3 }); // filtramos console.log( arreglo );

Version for EcmaScript 2015:

 var arreglo = [1,2,3,4,5]; arreglo = arreglo.filter((i) => i !== 3); // filtramos console.log( arreglo );
Scroll to Top