Home > Software design >  Javascript; pushing common elements from 2 lists to a new list
Javascript; pushing common elements from 2 lists to a new list

Time:11-10

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

const listOne = ["Bill", "Joe", "Trever", "Neil", "Jim", "Pam", "Michael"]
const listTwo = ["Petter", "Pam", "Steven", "Jim", "Michael", "Scott"]

const newList = listOne.filter(item => listTwo.indexOf(item) > -1)
console.log(newList)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related