Compare array objects and show difference

点点圈 提交于 2019-12-01 22:52:43

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(' '));

This should do the trick.

let completedList = [{id:1},{id:2},{id:3},{id:4},{id:7},{id:8}];
let invalidList = [{id:3},{id:4},{id:5},{id:6}];
// filter the items from the invalid list, out of the complete list
let temp1 = completedList.map(e => e.id);
let temp2 = invalidList.map(e => e.id);
let validList = temp1.filter(e => temp2.indexOf(e) === -1);
// find items only in invalidList
let difference = temp2.filter(e => temp1.indexOf(e) === -1);
console.log(validList); // Print [1,2,7,8]
console.log(difference);

I often rely on lodash implementation for comparison. In lo dash you can get the job done following manner

_.intersectionWith(arr1, arr2, _.isEqual) - For similarity _.differenceWith(arr1, arr2, _.isEqual) - for differences

This ans is confined to using a util library to get the job done. If you are looking for the exact algo I would definitely take some time to develop it and reply as a comment to this post .

Thanks

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

//get the items that are in the invalid list but not completed list
var filteredList1 = invalidList.filter((invalidListItem) => !completedList.find((item) => item.id === invalidListItem.id));

//get the items that are in  the completed list but not in the invalid list
var filteredList2 = completedList.filter((completedListItem) => !invalidList.find((item) => item.id === completedListItem.id));

//join the two arrays
var difference = filteredList1.concat(filteredList2);

//display the merged array and sort
console.log(difference.sort((item1, item2) => { return item1.id > item2.id ? 1 : item1.id < item2.id ? -1 : 0; }));

//outputs 1,2,5,6,7,8
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!