I am trying to compare 2 lists and get the value difference between them
list1 = [01-0161045, 01-0161046, 01-0158587, 01-0158647, 01-0158262, 01-0158264]
list2 = [01-0161045, 01-0161046, 01-0158587, 01-0158647, 01-0158262, 01-0158263, 01-0158265]
In the above 2 lists, first I need to compare list2 with list1 and differences are "01-0158263" and "01-0158265". This difference needs to be spitted to a different list (say list3)
list3 = [01-0158263, 01-0158265]
Next, I compare list1 with list2 and difference is "01-0158264". This value needs to be appended to end of list2. We can save the results to list4.
list4 = [01-0161045, 01-0161046, 01-0158587, 01-0158647, 01-0158262, 01-0158263, 01-0158265, 01-0158264].
I have tried doing it using 2 for loops in Google Apps Script but it takes a long time when the list grows. Just wondering is there a way to do it efficiently using list comparison.
Thanks for your help !!
In order to achieve your goal, how about the following sample script? In this sample script, 2 objects are created from list2
and list3
. And, using these objects, list3
and list4
are created.
const list1 = ["01-0161045", "01-0161046", "01-0158587", "01-0158647", "01-0158262", "01-0158264"];
const list2 = ["01-0161045", "01-0161046", "01-0158587", "01-0158647", "01-0158262", "01-0158263", "01-0158265"];
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]));
console.log(list3)
console.log(list4)