Here is my array:
export const plantList = [
{
name: 'monstera',
category: 'classique',
id: '1ed'
},
{
name: 'ficus lyrata',
category: 'classique',
id: '2ab'
},
{
name: 'pothos argenté',
category: 'classique',
id: '3sd'
},
{
name: 'yucca',
category: 'classique',
id: '4kk'
},
{
name: 'olivier',
category: 'extérieur',
id: '5pl'
},
{
name: 'géranium',
category: 'extérieur',
id: '6uo'
},
{
name: 'basilique',
category: 'extérieur',
id: '7ie'
},
{
name: 'aloe',
category: 'plante grasse',
id: '8fp'
},
{
name: 'succulente',
category: 'plante grasse',
id: '9vn'
}
]
And here is my code to remove the duplicate values:
const categories = plantList.reduce(
(acc, plant) =>
acc.includes(plant.category) ? acc : acc.concat(plant.category),
[]
);
Is there a better way to do this? I don't know why but React doesn't compile with the one-liner.
const categories = Array.from(new Set(plantList));
I think the best approach is using reduce and Map object. This is a single line solution.
const plantList = [
{
name: 'monstera',
category: 'classique',
id: '1ed'
},
{
name: 'ficus lyrata',
category: 'classique',
id: '2ab'
},
{
name: 'pothos argenté',
category: 'classique',
id: '3sd'
},
{
name: 'yucca',
category: 'classique',
id: '4kk'
},
{
name: 'olivier',
category: 'extérieur',
id: '5pl'
},
{
name: 'géranium',
category: 'extérieur',
id: '6uo'
},
{
name: 'basilique',
category: 'extérieur',
id: '7ie'
},
{
name: 'aloe',
category: 'plante grasse',
id: '8fp'
},
{
name: 'succulente',
category: 'plante grasse',
id: '9vn'
}
];
const uniqueData = [...plantList.reduce((map, obj) => map.set(obj.category, obj), new Map()).keys()];
console.log(uniqueData)