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

1

I have an array of objects and I need to delete an object from this array but I do not know what index that object occupies in the array, how can I remove that object from within the array?     

asked by anonymous 29.09.2017 / 16:54

3 answers

6

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 findIndex and then use .splice or use .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);
    
29.09.2017 / 17:00
0

One way to do this is by searching the Array for the index of the object 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);
    
29.09.2017 / 17:01
0

Using indexOf and splice

Look for the item inside the array and once you know the index, remove the item:

var index = meuArray.indexOf("minhaChave");
meuArray.splice(index, 1);
    
29.09.2017 / 17:00