简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM