Search code examples
javascriptecmascript-6ecmascript-5

Compare array objects and show difference


I have two arrays which I want to compare and check if there is an deleted item in one of these arrays. If there is show me the difference (deleted item)

Here is the code below how I would like to achieve this:

 var completedList = [{id:1},{id:2},{id:3},{id:4},{id:7},{id:8}];
    var invalidList = [{id:3},{id:4},{id:5},{id:6}];

    // filter the items from the invalid list, out of the complete list
    var validList = completedList.map((item) => {
        console.log(item.id)
        return item.id;
        //console.log(invalidList.id);
    }).filter(item => {
        Object.keys(invalidList).map(key => {
            console.log(invalidList[key].id)
            //return !invalidList[key].id.includes(item.id);
        });
    })

    console.log(validList); // Print [1,2,7,8]

    // get a Set of the distinct, valid items
    var validItems = new Set(validList);

But this returns me a lot of id's how can I map through both array's and filter on object property id? And only show the difference between these array objects.

So basically what I expect is to see the difference between those arrays so log the differences in id's so in this example: 1,2,5,6,7,8


Solution

  • You could take a Set for getting a difference. For getting the differences from each other (a symmetric difference), you need to get both differences.

    const
        difference = (a, b) => Array.from(b.reduce((s, v) => (s.delete(v), s), new Set(a))),
        getId = ({ id }) => id;
    
    var completedList = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 7 }, { id: 8 }],
        invalidList = [{ id: 3 }, { id: 4 }, { id: 5 }, { id: 6 }],
        complete = completedList.map(getId),
        invalid = invalidList.map(getId),
        left = difference(complete, invalid),
        right = difference(invalid, complete),
        result = [...left, ...right]
    
    console.log(result.join(' '));
    console.log(left.join(' '));
    console.log(right.join(' '));