Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save pietrop/351d8ee463d85a69b75b2c2cbbf84a02 to your computer and use it in GitHub Desktop.
Save pietrop/351d8ee463d85a69b75b2c2cbbf84a02 to your computer and use it in GitHub Desktop.
Pluck Unique Values from Array of Javascript Objects

Pluck Unique Values from Array of Javascript Objects

Implementation

const pluck = key => array => Array.from(new Set(array.map(obj => obj[key])));

Usage

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));

Output

[
  "Audi",
  "Ferarri",
  "Ford",
  "Peugot"
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment