Skip to content Skip to sidebar Skip to footer

Compare Two Array Of Objects And Filter Element Not Present In Second Array

Suppose I have two array of object as: const array1 = [ { name: 'detail1', title: 'detail1' }, { name: 'detail2 ', title: 'detail2 ' }, { name: 'detail3', title: 'detail3' },

Solution 1:

You could build a normalised object with key and values and filter the objects.

const
    array1 = [{ name: 'detail1', title: 'detail1' }, { name: 'detail2 ', title: 'detail2 ' }, { name: 'detail3', title: 'detail3' }, { name: 'detail4', title: 'detail4' }, { name: 'detail5', title: 'detail6' }, { name: 'detail7', title: 'detail7' }, { name: 'detail8', title: 'detail8' }],
    array2 = [{ name: 'detail1', title: 'detail1' }, { name: 'detail2 ', title: 'detail2 ' }, { name: 'detail3', title: 'detail3' }, { name: 'detail4', title: 'detail4' }],
    sortEntriesByKey = ([a], [b]) => a.localeCompare(b),
    filter = array2.reduce((r, o) => {
        Object
            .entries(o)
            .sort(sortEntriesByKey)
            .reduce((o, [k, v]) => (o[k] ??= {})[v] ??= {}, r);
        return r;
    }, {});
    absent = array1.filter((o) => {
        let f = filter;
        return !Object
            .entries(o)
            .sort(sortEntriesByKey)
            .every(([k, v]) => f = f[k]?.[v]);
    });

console.log(absent);
.as-console-wrapper { max-height: 100%!important; top: 0; }

Solution 2:

Edit: you want objects in A not in B. It is ideal to loop through A, find if the element exists in B. If yes, then do not include it.

In javacript object references are compared when you do "==" or "===" or other array search methods.

{} == {} will return false. You can check in your dev console.

In your case, you will have to check specific properties.

var absent = array1.filter(e=>{
  let findInd = array2.findIndex((a)=>{
    return (a.name == e.name && a.title == e.title);});
return (findInd == -1); });

In the inner findIndex, I am finding index based on a condition. In filter method, I am returning true only if that index is -1(not found).

Post a Comment for "Compare Two Array Of Objects And Filter Element Not Present In Second Array"