I'm working on a checkbox ui react web app, where in, on check we dispatch items array with a object in it, and on uncheck also we dispatch items array with object in it. So I need to add this logic - Check if object of any array exist in an another array, if not exists then push onto another array , or else remove it from another array
let items1 = [{ name: "a" }, { name: "b" }, { name: "c" }];
let items2 = [{ name: "a" }, { name: "d" }, { name: "e" }];
const commonItems = items1.filter((x) => items2.some((y) => y.name === x.name));
if (!commonItems) {
items1.push(...items2);
} else {
items1 = items1.filter((x) => items2.some((y) => y.name !== x.name));
}
console.log(items1);
console.log(items2);
Check if object of any array exist in an another array, if not exists then push onto another array , or else remove it from another array, Is this code corect for above logic?
Couple of issues. 1) commonItems is always a truth value because filter returns empty array when no results, so always going to else block 2) Else block filter is not correct. (updated here to use !some)
let items1 = [{ name: "a" }, { name: "b" }, { name: "c" }];
let items2 = [{ name: "a" }, { name: "d" }, { name: "e" }];
const commonItems = items1.filter((x) => items2.some((y) => y.name === x.name));
console.log(commonItems)
if (commonItems.length < 1) {
items1.push(...items2);
} else {
items1 = items1.filter((x) => !items2.some((y) => y.name === x.name));
}
console.log(items1);
console.log(items2);