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!
asked May 4, 2018 at 8:32
Ciprian
3,22610 gold badges68 silver badges101 bronze badges
2 Answers 2
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)
answered May 4, 2018 at 8:34
Ori Drori
196k32 gold badges243 silver badges233 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
answered May 4, 2018 at 8:39
Sasha
5,9441 gold badge22 silver badges38 bronze badges
Comments
lang-js