How to remove multiple values from array using javascript?

1.9k views Asked by At
var array = [{
    name: "Mango",
    weight: "15gm"
}, {
    name: "Banana",
    weight: "10gm"
}, {
    name: "Apple",
    weight: "15gm"
}, {
    name: "Grapes",
    weight: "5gm"
}, {
    name: "Banana",
    weight: "15gm"
}];

I want to remove all other than Banana.

2

There are 2 answers

3
Luke On

See here.

array.filter(function(x) {
    return x.name == "Banana";
});

So given this input:

[{"name":"Mango","weight":"15gm"},{"name":"Banana","weight":"10gm"},{"name":"Apple","weight":"15gm"},{"name":"Grapes","weight":"5gm"},{"name":"Banana","weight":"15gm"}]

We get this output:

[{"name":"Banana","weight":"10gm"},{"name":"Banana","weight":"15gm"}]
0
user3639680 On

In above array when i remove array element using splice method my array length decremented by 1 so I have to consider index i. Following is a code to remove such objects.

for(var i=0;i<array.length;i++){
   if(array[i].name !== "Banana"){
       array.splice(i,1);
       i--;
   }
}