Not just one. There are a lot of methods available for this. Basically you need a looping logic.
Please find the Array.reduce
implementation.
Logic
- Create a merged array, by using spread operator.
- Check each node of merged array in accumulator.
- If the node from the merged array, doesnot exist in accumulator, then its unique.
Working Fiddle
let array1 = [{ categoryName: "category 1" },{ categoryName: "category 2" },{ categoryName: "category 3" },{ categoryName: "category 4" }];
let array5 = [{ categoryName: "category 1" },{ categoryName: "category 2" },{ categoryName: "category 3" },{ categoryName: "category 4" },{ categoryName: "category 5" }];
const uniqueValues = [...array1, ...array5].reduce((acc, curr) => {
const nodeExist = acc.some(item => item.categoryName === curr.categoryName);
const secondArrayExist = array5.some(item => item.categoryName === curr.categoryName);
if (!nodeExist) {
acc.push(curr);
}
return acc;
}, []);
console.log(uniqueValues);
If you want to get the nodes which are present in only in any one of the array, use the below logic.
Logic
- Create a merged array.
- Check each node in the merged array, whether its present in
array1
and array5
. If the node is not present in any one of array1
or array5
then this is unique node.
- Push that node to accumulator.
Working Fiddle
let array1 = [{ categoryName: "category 1" },{ categoryName: "category 2" },{ categoryName: "category 3" },{ categoryName: "category 4" }];
let array5 = [{ categoryName: "category 1" },{ categoryName: "category 2" },{ categoryName: "category 3" },{ categoryName: "category 4" },{ categoryName: "category 5" }];
const uniqueValues = [...array1, ...array5].reduce((acc, curr) => {
const firstArrayExist = array1.some(item => item.categoryName === curr.categoryName);
const secondArrayExist = array5.some(item => item.categoryName === curr.categoryName);
if (!firstArrayExist || !secondArrayExist) {
acc.push(curr);
}
return acc;
}, []);
console.log(uniqueValues);