¿Cómo eliminar un elemento de una matriz en JavaScript?


var arr = [1,2,3,5,6];

Quiero eliminar el 1er elemento de la matriz para que se convierta en:

var arr = [2,3,5,6];

Para extender esta pregunta, ¿qué pasa si quiero eliminar el segundo elemento de la matriz para que se convierta en:

var arr = [1,3,5,6];
Author: Samuel Liew, 2010-01-05

9 answers

Para una solución más flexible, utilice el splice() función. Le permite eliminar cualquier elemento en una matriz basada en el valor de índice:

var indexToRemove = 0;
var numberToRemove = 1;

arr.splice(indexToRemove, numberToRemove);
 315
Author: Gabriel McAdams,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-08 12:09:56

shift() es ideal para su situación. shift() elimina el primer elemento de una matriz y devuelve ese elemento. Este método cambia la longitud de la matriz.

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

array.shift(); // 1

array // [2, 3, 4, 5]
 649
Author: JP Silvashy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-30 20:46:39

El método Array.prototype.shift elimina el primer elemento de una matriz y lo devuelve. Modifica la matriz original.

var a = [1,2,3]
// [1,2,3]
a.shift()
// 1
a
//[2,3]
 54
Author: Ped,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-28 08:43:42
arr.slice(begin[,end])

No es destructivo, splice and shift modificará su matriz original

 36
Author: kiuma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-18 07:29:50

Escribió un pequeño artículo sobre insertar y eliminar elementos en posiciones arbitrarias en matrices Javascript.

Aquí está el pequeño fragmento para eliminar un elemento de cualquier posición. Esto extiende la clase Array en Javascript y agrega el método remove (index).

// Remove element at the given index
Array.prototype.remove = function(index) {
    this.splice(index, 1);
}

Así que para eliminar el primer elemento de tu ejemplo, llama a arr.remove ():

var arr = [1,2,3,5,6];
arr.remove(0);

Para eliminar el segundo elemento,

arr.remove(1);

Aquí hay un pequeño artículo con métodos de inserción y eliminación para matriz clase.

Esencialmente esto no es diferente de las otras respuestas que usan splice, pero el nombre splice no es intuitivo, y si tiene esa llamada en toda su aplicación, solo hace que el código sea más difícil de leer.

 13
Author: Anurag,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-10 06:48:54

Tal vez algo como esto:

arr=arr.slice(1);
 10
Author: ThatGuyYouKnow,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-27 13:02:53

Si desea eliminar uno o varios elementos de un array depende su contenido y/o su posición.

Puede usar la función de matriz js filter.

Https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/filter.

Eliminar el primer elemento :

// Not very useful but it works
function removeFirst(element, index) {
  return index > 0;
}
var arr = [1,2,3,5,6].filter(removeFirst); // [2,3,4,5,6]

Eliminar el segundo elemento :

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

Eliminar elemento impar :

function removeOdd(element, index) {
  return !(element % 2);
}
var arr = [1,2,3,5,6].filter(removeOdd); [2,4,6]
 2
Author: Martin Choraine,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-05 13:58:38

Puede utilizar la función de Asignación de Desestructuración ES6 con un operador rest. Una coma indica dónde desea eliminar el elemento y el resto (...arr) para darle los elementos restantes de la matriz.

const source = [1,2,3,5,6];

function removeFirst(list) {
   var  [, ...arr] = source;
   return arr;
}
const arr = removeFirst(source);
console.log(arr); // [2, 3, 5, 6]
console.log(source); // [1, 2, 3, 5, 6]
 0
Author: Brendan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-07 22:04:00

Array.splice() tiene la interesante propiedad de que no se puede utilizar para eliminar el primer elemento. Por lo tanto, tenemos que recurrir a

function removeAnElement( array, index ) {
    index--;

    if ( index === -1 ) {
        return array.shift();
    } else {
        return array.splice( index, 1 );
    }
}
 -1
Author: Gabriel Schulhof,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-23 07:31:18