I am trying to compare 2 lists based on 2 different columns and get the difference.
const list1 = [[121,"7/2/2019"], [131,"7/22/2019"], [141, ]]
const list2 = [[121, ], [131, ], [141, ]]
In the above 2 lists, I am trying to compare list1 with list2 based on the 2 columns - col1 and col2. First columnn (col1) [121,131,141] will always be the same in both the lists.
For every unique column 1 (col1) [121,131,141] in list1, compare the corresponding element in list2 based on second column, and if it is different, I am trying to output it to a different list
Result = [[121,"7/2/2019"], [131,"7/22/2019"]
Another example is
const list1 = [[121,"7/2/2019"], [131,"7/22/2019"], [141, ]]
const list2 = []
Result = [[121,"7/2/2019"], [131,"7/22/2019"], [141, ]]
I tried with the below code but it does not yield my desired result
const obj1 = list1.reduce((o, e) => Object.assign(o, {[e]: true}), {});
const obj2 = list2.reduce((o, e) => Object.assign(o, {[e]: true}), {});
const list3 = list2.filter(e => !obj1[e]);
const list4 = list2.concat(list1.filter(e => !obj2[e]));
Any leads/suggestions would be appreciated.
Try this to compare rows in list1
to the rows in list2
that appear at the same position in their respective arrays:
const difference = list1.filter((row, index) => row[1] !== list2[index][1]);
If the rows are not guaranteed to appear in the same position, try this:
const list1 = [[121, "7/2/2019"], [131, "7/22/2019"], [141,]];
const list2 = [[121,], [131,], [141,]];
const difference = list1.filter((row1, index) => {
const list2row = list2.filter(row2 => row2[0] === row1[0])[0];
return !Array.isArray(list2row) || row1[1] !== list2row[1];
});