How to remove an item from an array without knowing the index, only the value?

Asked

Viewed 3,932 times

1

I have an object array and I need to delete an object from that array but I don’t know the index that that object occupies in the array, as I can remove that object from inside the array?

3 answers

8


In simple arrays you can do:

var arr = ['a', 'b', 'c'];
arr.splice(arr.indexOf('b'), 1);

console.log(arr);

In object arrays:

You can use the findIndex and then use the .splice or else use the .filter and create a new array:

With .filter()

var arr = [{
  valor: 1
}, {
  valor: 2
}, {
  valor: 3
}];

var numeroARemover = 3;

arr = arr.filter(obj => obj.valor != numeroARemover);
console.log(arr);

With .findIndex and .splice

var arr = [{
  valor: 1
}, {
  valor: 2
}, {
  valor: 3
}];

var numeroARemover = 3;

var indice = arr.findIndex(obj => obj.valor == numeroARemover);
arr.splice(indice, 1);
console.log(arr);

2

Using indexOf and splice

Search the item inside the array and after knowing the index remove the item:

var index = meuArray.indexOf("minhaChave");
meuArray.splice(index, 1);
  • var a = [1,2,3]; var i = a.indexOf(2); a.splice(i - i, 1); gives [2, 3] - That one .splice(index - 1, 1); should be .splice(index, 1);

  • You’re right... I corrected it here. I took an example that was like this. rs

  • In this case you can comment in the example that there is wrong :P

0

One way to do this is by searching the Array for the object’s index and then removing it with .splice():

var a = new Array("um","dois","tres");
console.log("Array original:"+ a);
var indice = a.indexOf("dois"); // quero remover "dois" da Array
a.splice(indice, 1);
console.log("Array após:"+ a);

Browser other questions tagged

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