how do I filter out array of objects a
, where item1 is part of array b
?
a = [
{
"item1": "apple",
"item2": "banana"
},
{
"item1": "apple",
"item2": "cherry"
},
{
"item1": "melon",
"item2": "cherry"
},
{
"item1": "banana",
"item2": "melon"
}]
b = [ "apple", "banana"]
the expected array would be:
expected_array = [{
"item": "melon",
"item2": "cherry"
}]
I tried with:
a.filter(el => !b.includes(el.item1))
but the resulting array has the same length as the original.
I am doing this in Node Red where this is my test setup:
[{"id":"ab67374c.c64458","type":"debug","z":"42edc0b9.7ba91","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","statusVal":"","statusType":"auto","x":2040,"y":300,"wires":[]},{"id":"3fbdbc18.951c94","type":"function","z":"42edc0b9.7ba91","name":"cycle counter","func":"\n\nmsg.payload = msg.payload.filter(el => !msg.exclude.includes(el.altname));\n\nnode.warn(msg.payload);\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":1810,"y":320,"wires":[["ab67374c.c64458"]]},{"id":"b4b2e91f.8e4368","type":"inject","z":"42edc0b9.7ba91","name":"","props":[{"p":"payload"},{"p":"exclude","v":"[[\"melon\"],[\"banana\"]]","vt":"json"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"[{\"altname\":\"melon\"},{\"altname\":\"cherry\"},{\"altname\":\"banana\"}]","payloadType":"json","x":1650,"y":320,"wires":[["3fbdbc18.951c94"]]}]
As others have said in comments, your code is fine but you need to assign the filter function's output to a variable.
let a = [{
"item1": "apple",
"item2": "banana"
},
{
"item1": "apple",
"item2": "cherry"
},
{
"item1": "melon",
"item2": "cherry"
},
{
"item1": "banana",
"item2": "melon"
}
];
let b = ["apple", "banana"];
// assign filter output to variable `c`
let c = a.filter(el => !b.includes(el.item1));
console.log(c); // your output