0

I am trying to filter an array object with array value, here the code:

const array1 = [{
            "packaging": "Box",
            "price": "100"
        }, {
            "packaging": "Pcs",
            "price": "15",
        }, {
            "packaging": "Item",
            "price": "2",
        }];

const b = ['Pcs','Item']
const found = array1.filter(el => {
    for(i = 0; i < b.length; i++) {
      return el.packaging !== b[i];
    }
});

console.log(found);

my expected output is array with object doesnt not exist in b [{ packaging: "Box", price: "100" }]

1
  • Your nested for loop is unnecessary, .filter already loops over the elements. Do as the answers below say and just return the desired condition right away (using .includes) Commented Dec 11, 2020 at 5:34

3 Answers 3

4

Use an .includes check instead:

const array1 = [{
            "packaging": "Box",
            "price": "100"
        }, {
            "packaging": "Pcs",
            "price": "15",
        }, {
            "packaging": "Item",
            "price": "2",
        }];

const b = ['Pcs','Item']
const found = array1.filter(el => !b.includes(el.packaging));
console.log(found);

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

2 Comments

That was a quick one using includes instead of b.indexOf(item) == -1. :) However, would you always suggest using includes ahead of old-fashioned way, in terms of performance? Or both are equal?
.includes might be a bit faster since it doesn't have to look at the index, just return a boolean - but what matters far more in real world situations is readability, 95% of the time, which .includes wins hands-down.
0

You should do the following,

const array1 = [{
            "packaging": "Box",
            "price": "100"
        }, {
            "packaging": "Pcs",
            "price": "15",
        }, {
            "packaging": "Item",
            "price": "2",
        }];

const b = ['Pcs','Item']
const found = array1.filter(el => {
    return b.findIndex(item => item === el.packaging) <= -1;
});

console.log(found);

Comments

0

Does this solve your problem?

const arr1 = [
  {"packaging": "Box", "price": "100"}, 
  {"packaging": "Pcs", "price": "15"}, 
  {"packaging": "Item", "price": "2"}
];

const arr2 = ['Pcs','Item'];
const found = arr1.filter(item => {
  return arr2.indexOf(item.packaging) === -1;
});

console.log(found);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.