user3639680
user3639680

Reputation: 71

How to remove multiple values from array using javascript?

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.

Upvotes: 0

Views: 1996

Answers (2)

Luke
Luke

Reputation: 1724

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"}]

Upvotes: 2

user3639680
user3639680

Reputation: 71

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--;
   }
}

Upvotes: 1

Related Questions