Remove more than one item from an array

Asked

Viewed 3,515 times

9

It is possible to remove more than one item from an array at a time.

Follows 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 goes 'crazy' because it has one less item or all indexes change

  • Have you tried teste.splice(1, 2), without running the others you already have? The second splice parameter is the amount to be removed. More on MDN

2 answers

10


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

So stay 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 method 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"]
  • Thanks Hezekiah, I was unaware of this 'filter' function of the array, I was able to accomplish the task using a for and a while but it wasn’t very beautiful, it was functional only. This certainly will help a lot in the next ones. Thanks !

3

The first parameter is the parti from which Dice will start to be removed, and the second how many positions 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

  • Ola Marconi, thanks for the reply but I put it as an example, ie not always the items to be deleted will be last or in sequence. I’m almost there as soon as I finish putting the answer. Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.