0

I would like to know the best way to push values from multiple objects to an array while keeping them unique.

For example:

let emails = [];

owners.map(data => {
    emails.push(data.mail)
})

members.map(data => {
    emails.push(data.mail)
})

console.log(emails) 

emails gets populated with the emails from each object, but they are duplicates. I know how to filter an array for duplicates, but I want to see more options for the above code. Thanks!

2 Answers 2

3

Using array spread combine both arrays to a single array, and map the array to an array of emails. Convert the array to a Set to remove duplicates, and spread back to array:

const members = [
  { mail: '[email protected]' },
  { mail: '[email protected]' },
];

const owners = [
  { mail: '[email protected]' },
  { mail: '[email protected]' },
];

const emails = [...new Set([...members, ...owners].map(data => data.mail))];

console.log(emails)

Sign up to request clarification or add additional context in comments.

Comments

0

As Ori mentioned, use Set

const emails = new Set();

owners.map(data => {
    emails.add(data.mail)
})

members.map(data => {
    emails.add(data.mail)
})

console.log(Array.from(emails)) //if you need it back to array

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.