One of my students is making a project that has two lists. The lists share some values in common but not all and the student is trying to make a third list that only stores the elements they have in common. I want to find the simplest way possible for them to do this.
For example if list1 stores [a, b, c, d]
And list2 stores [e, a, f, c]
list3 should be [a, c]
I just want to find a very simple way to do this so my student can fully understand it. Thanks!
I don’t know if this is the simplest solution but, I’ll show it first and then walk you through what i did
// Variable initialization
var list1 = ['a', 'b', 'c', 'd'];
var list2 = ['e', 'a', 'f', 'c'];
var list3 = [];
// Algorithm
for(var l1 = 0; l1 < list1.length; l1++) { // looks through 1st array
for(var l2 = 0; l2 < list2.length; l2++) { // looks through the 2nd
// this compares every element of list 2 to list 1 any that match get added
if(list1[l1] == list2[l2]) {
appendItem(list3, list1[l1]) // could also use list2[l2] in second parameter
}
}
}
// Result
console.log(list3)
I could have used .indexOf as well to spare your eyes from this but this is basically what that is doing much like you go down a shopping list to find anything missing this is basically an automated version of that and anything that matches will be added in list3 as the result