1

I have an object data coming from service, i want to filter out some items based on key-value, also it's not only one item but multiple items to remove;

var dataFromServce = [{
    kod: 1000, teur: 'do0',    
    kod: 1001, teur: 'do1',   
    kod: 1002, teur: 'do2',    
    kod: 1003, teur: 'do3'

}];
var removeItems = [1001, 1002, 1003];

if (removeItems != "") {

    // run thru dataFromServce loop

    for (var i = 0; i < dataFromServce.length; i++) {
        // if dataFromServce item match removeItems then remove it from dataFromServce
        // TODO: to match every item in removeItems
        if (dataFromServce[i].kod === removeItems[0]) {
            dataFromServce.splice(i, 1);

            i--;

        }

    }

this way it checks only one item (removeItems[0]) result should be

var dataFromServce = [{
    kod: 1000, teur: 'do0'     
}];

1 Answer 1

2

You're looking for filter and includes

const dataFromService = [{
  kod: 1000,
  teur: 'do0'
}, {
  kod: 1001,
  teur: 'do1'
}, {
  kod: 1002,
  teur: 'do2'
}, {
  kod: 1003,
  teur: 'do3'
}];
const removeItems = [1001, 1002, 1003];

const res = dataFromService.filter(({
  kod
}) => !removeItems.includes(kod));
console.log(res);

The code in your question is obviously wrong since your dataFromService is invalid, I've fixed that in the answer.

Sign up to request clarification or add additional context in comments.

3 Comments

This snippet has O(m*n) complexity, where m and n are sizes of input and filter. This can be improved to O(m*log n) by using hash instead of array for filter or using binary search for key (filter array should be sorted beforehand). Furthermore, if both input and filter come already sorted, improvement is possible to O(m+n)
thank you for your answer @VasilyLiaskovsky , but there is one problem...its not working on internet explorer.
needs refactor to dataFromService.filter(({kod}) => !removeItems.includes(kod));

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.