Search code examples
javascriptecmascript-6ecmascript-5

filter array object with array value


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


Solution

  • 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);