let listOne = [Bill, Joe, Trever, Neil, Jim, Pam, Michael]
let listTwo = [Petter, Pam, Steven, Jim, Michael, Scott]
I have two lists but I want to create a new list with only the names in both lists.
[Jim, Pam, Michael]
What I did:
I create a nested loop to push each name into a new list
what I need help with:
I feel there is a better way to do this. without having to nest my loops. Perhaps somehow filtering through both lists simultaneously somehow
You can make use of Set and filter here. Checking the existence of name in Set is efficient, if you gonna use has method of set.
let listOne = ["Bill", "Joe", "Trever", "Neil", "Jim", "Pam", "Michael"];
let listTwo = ["Petter", "Pam", "Steven", "Jim", "Michael", "Scott"];
const set = new Set(listOne);
const result = listTwo.filter(name => set.has(name));
// or
// const result = listTwo.filter(set.has.bind(set));
console.log(result);
You could use Array.prototype.reduce, have the callback search the other list, and only insert the name if it is in the other list.
listOne.reduce((prev, cur)=>{
if(listTwo.includes(cur)){
prev.push(cur);
}
return prev;
});
EDIT: After further testing, Array.prototype.reduce requires the first and second arguments to have a type of number, so I would recommend using filter instead. (see other answers)
However, if you want to use reduce, you would have to use something like this:
let listOne = ["Bill", "Joe", "Trever", "Neil", "Jim", "Pam", "Michael"];
let listTwo = ["Petter", "Pam", "Steven", "Jim", "Michael", "Scott"];
let results = [];
listOne.reduce((prev, cur)=> {
if(listTwo.includes(cur)){
results.push(cur);
}
return;
});
console.log(results); // Prints [ 'Jim', 'Pam', 'Michael' ]
My recommendation is to use the accepted answer by Vitor Franca and use Array.prototype.filter
You can do something like this:
let listOne = [Bill, Joe, Trever, Neil, Jim, Pam, Michael]
let listTwo = [Petter, Pam, Steven, Jim, Michael, Scott]
let result = listOne.filter(item => listTwo.includes(item))