Remove more than one item from an array

9

You can remove more than one item from an array at a time.

Follow the code:

var teste = [6,4,5];
//meu objectivo é remover os itens 4, 5 por ex

//removendo o item 4
teste.splice(1, 1)

//removendo o item 5
teste.splice(1, 2)

As you can see after I remove the first item the array is 'crazy' because it has one less item ie all indexes change

    
asked by anonymous 12.02.2015 / 18:50

2 answers

10

The first argument of splice is one index in the array, the second is the amount of items to remove from there.

So it looks like this:

var itens = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var indice = 2; // lembre que começa em zero, então esta é a posição do "c"
var quantidade = 3;

var removidos = itens.splice(indice, quantidade);

console.log(itens); // ["a", "b", "f", "g"]
console.log(removidos); // ["c", "d", "e"]

If you do not know the position of the items, you can remove items using the filter :

var itens = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];

var resultado = itens.filter(function(item) {
  return item !== 'c' &&  item !== 'e';
});

console.log(resultado); // ["a", "b", "d", "f", "g"]

or so to make it easier:

var itens = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var remover = ['f', 'c'];

var resultado = itens.filter(function(item) {
  return !~remover.indexOf(item);
});

console.log(resultado); // ["a", "b", "d", "e", "g"]

If you want to do a function to use other times:

function remover(array, rem) {
  return array.filter(function(item) {
    return !~rem.indexOf(item);
  });
}

var original = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var resultado1 = remover(original, ['f', 'c']);
var resultado2 = remover(original, ['a', 'e', 'g']);

console.log(resultado1); // ["a", "b", "d", "e", "g"]
console.log(resultado2); // ["b", "c", "d", "f"]
    
12.02.2015 / 19:24
3

The first parameter is the one from which index will begin to be removed, and the second will be removed. In my example I'm saying:

Remove 1 element from position 1.

See working:

var fruits = [6,4,5];
    
fruits.splice(1, 1);

console.log(fruits);

Source: W3Scholls

    
12.02.2015 / 19:16