Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
Javascript; pushing common elements from 2 lists to a new list
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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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))
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!