const pluck = key => array => Array.from(new Set(array.map(obj => obj[key])));
const cars = [
{ brand: 'Audi', color: 'black' },
{ brand: 'Audi', color: 'white' },
{ brand: 'Ferarri', color: 'red' },
{ brand: 'Ford', color: 'white' },
{ brand: 'Peugot', color: 'white' }
];
const getBrands = pluck('brand');
console.log(getBrands(cars));
[
"Audi",
"Ferarri",
"Ford",
"Peugot"
]
A
pluck
function does not do inner loops so it isn't a good fit for that @rognales. You could get nested properties with a modifiedpluck
that takes a path likepluck('child.grandChild.greatGrandChild')
for example, but your data has an Array ofcolors
where you want to do an inner loop to get all of them. If you wanted to only get the first color from each Car for example,pluck
would be relevant there because you could dopluck('colors.0')
which would return[{ color: "Black" }, { color: "Black" }, { color: "Blue" }, { color: "Blue" }]
but that's not what you want.Maybe something bespoke like this would be better for that situation:
Output