MomasVII
MomasVII

Reputation: 5071

Collect unique values of array in an array React

Can someone let me know how I can create a list of unique languages from an array inside another array.

This is the dataset...

const people = [
{
    //Other values, name date etc.
    languages: ["English", "Spanish"]
},{
    //Other values, name date etc.
    languages: ["English", "Mandarlin"]
},{
    //Other values, name date etc.
    languages: ["Japanese"]
},....

and here is as far as I've got....

const languagesOptions = this.props.data.map((item, index) => {
  new Map(
    ...item.languages.map(d => [d.languages])
  )
});

I can use the new Map function when it's not an array but can't get it to work with the languages data.

Thanks

Upvotes: 1

Views: 797

Answers (1)

kind user
kind user

Reputation: 41893

You could map over it and use Set to remove dupes.

const people = [{
  languages: ["English", "Spanish"]
}, {
  languages: ["English", "Mandarlin"]
}, {
  languages: ["Japanese"]
}];

const languages = [...new Set(people.flatMap(({ languages }) => languages))];

console.log(languages);

Upvotes: 1

Related Questions