js-icon

Javascript: Eliminar un item de un array por su nombre

Pongan esto en su codigo:

Array.prototype.removeItem = function (a) {
    for (var i = 0; i < this.length; i++) {
      if (this[i] == a) {
        for (var i2 = i; i2 < this.length - 1; i2++) {
          this[i2] = this[i2 + 1];
        }
        this.length = this.length - 1;
        return;
      }
    }
  };

Y ya podemos eliminar elementos del array:

var frutas = ['manzana', 'banana', 'pera'];
frutas.removeItem('banana');
console.log(frutas); // Entrega ['manzana', 'pera']

Chau!

Featured sites

    Comentarios

    1. Rolando

      Puedes utilizar también:

      var frutas = ['manzana', 'banana', 'pera'];
      var index = frutas.indexOf('banana');
      if (index > -1) {
      frutas.splice(index, 1);
      }
      console.log(frutas); // Entrega ['manzana', 'pera']

      Lo malo es que indexOf no es soportado en IE7-8, por lo que pudieras hacer entonces, el mismo código que tienes pero en vez de hacer esto:

      for (var i2 = i; i2 < this.length - 1; i2++) {
      this[i2] = this[i2 + 1];
      }
      this.length = this.length - 1;

      Puedes simplemente hacer esto:

      this.splice(i, 1);

      Salu2.

      Responder

    Deja un comentario

    Tu dirección de correo electrónico no será publicada. Los campos necesarios están marcados *

    Puedes usar las siguientes etiquetas y atributos HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>