简体   繁体   中英

Lodash compare array of objets different length

I'm using lodash to compare two arrays of objets with differentWith (isEqual) function.

Here my two arrays:

array1

[
    {
        "id":"28884",
        "designation":"French fries",
        "description":"French fries",
        "prices":[ 
            { 
            "price":0,
            "vat":2821
            }
        ]
    },
    {
        "id":"28885",
        "designation":"Potatoes",
        "description":"Potatoes",
        "prices":[ 
            { 
            "price":0,
            "vat":2821
            }
        ]
    }
]

array2

[
    {
        "id":"28884",
        "designation":"French fries",
        "description":"French fries",
        "prices":[ 
            { 
            "price":0,
            "vat":2821
            }
        ]
    },
    {
        "id":"28885",
        "designation":"Potatoes",
        "description":"Potatoes",
        "prices":[ 
            { 
            "price":0,
            "vat":2821
            }
        ]
    },
    {
        "id":"30157",
        "designation":"new item",
        "description":null,
        "prices":[ 
            { 
                "price":500,
                "vat":2821
            }
        ]
    }
]

Here what I did but it doesn't work:

const toAdd = _.differenceWith(array1, array2, _.isEqual);
const toRemove = _.differenceWith(array2, array1, _.isEqual);

How can I get removed element(s)? Moreover, How can I get the new elements, removed elements using lodash? Thank you !

The problem is the comparator in the code _.isEqual cannot compare two objects in the array. You could write a custom comparator.

A simpler vanilla js option may be

removedObjectsArray = array2.filter(item => !array1.map(obj => obj.id).includes(item.id));

Here the larger array is filtered to find items which have an id that is not in the smaller array.

You can use _.differenceBy. _.intersectionBy for comparision with key in case of array of objects.

.differenceBy .intersectionBy

 let toRemove = _.differenceBy(array2, array1, 'id');
 let toAdd = _.intersectionBy(array1, array2, 'id');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM