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?
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?
8
var arr = ['a', 'b', 'c'];
arr.splice(arr.indexOf('b'), 1);
console.log(arr);
You can use the findIndex
and then use the .splice
or else use the .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);
2
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);
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 javascript
You are not signed in. Login or sign up in order to post.
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);
– Sergio
You’re right... I corrected it here. I took an example that was like this. rs
– Alexandre Cavaloti
In this case you can comment in the example that there is wrong :P
– Sergio