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?
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?
var arr = ['a', 'b', 'c'];
arr.splice(arr.indexOf('b'), 1);
console.log(arr);
You can use findIndex
and then use .splice
or use .filter
and create a new array:
.filter()
var arr = [{
valor: 1
}, {
valor: 2
}, {
valor: 3
}];
var numeroARemover = 3;
arr = arr.filter(obj => obj.valor != numeroARemover);
console.log(arr);
.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);
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);
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);