Vik
Vik

Reputation: 9289

javascript delete matching rows of an array

i have an array structure like below from whch i need to delete all the entries having value vik

[{"type" :"x", value: "vik"},
{"type" :"x", value: "jack"},
{"type" :"x", value: "jack"},
{"type" :"x", value: "jack"},
{"type" :"x", value: "vik"},
{"type" :"x", value: "vik"},
]

iterating using for loop with splicing matching values vik screws up. what is the best way to do this.

my code is:

for(let obj of filterList){
        var i =0
        for(let lead of this.core.leadLocalList){
          console.log("comapring:" + lead.campaign)
          if(obj.value == lead.campaign){
            console.log("matched")
            this.core.leadLocalList.splice(i,1)
          }else
            i++
        }
    }

Upvotes: 0

Views: 549

Answers (2)

weirdpanda
weirdpanda

Reputation: 2626

You can use lodash. It's a dash-ing simple application.

With _.remove() like so:

_.remove( filterList, {
    value: 'vik'
} );

Or, with ES6, you can do the following:

const filtered = filterList.filter( row => row.value !== 'vik' );

However, if the application grows complex and you want something a little more advanced, you can take advantage of the predicate function and determine the filtering based on that:

_.remove( filterList, ( obj ) => {
    return ( obj.propertyOne !== SOME_CONSTANT ) && ( ... )
} );

Upvotes: 2

Lalit
Lalit

Reputation: 1369

You can use array filter method to get the desired result. Array Filter

var data = [{"type" :"x", value: "vik"},
{"type" :"x", value: "jack"},
{"type" :"x", value: "jack"},
{"type" :"x", value: "jack"},
{"type" :"x", value: "vik"},
{"type" :"x", value: "vik"},
];

const result = data.filter(item => item.value != "vik");
console.log(result);

Upvotes: 4

Related Questions