Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save JamieMason/bed71c73576ba8d70a4671ea91b6178e to your computer and use it in GitHub Desktop.
Save JamieMason/bed71c73576ba8d70a4671ea91b6178e 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"
]
@Mcklem
Copy link

Mcklem commented Mar 28, 2019

Brilliant!

@anewcoder1992
Copy link

very useful

@rognales
Copy link

How bout nested properties? Say i want to want to count colours. I should pluck the nested prop (colors.color == 'Black') then check for length. How do i do this?

const cars = [
  {
    "brand": "Audi",
    "model": "A1",
    "colors": [
      {
        "color": "Black"
      },
      {
        "color": "Blue"
      }
    ]
  },
  {
    "brand": "Ferrari",
    "model": "Spyder",
    "colors": [
      {
        "color": "Black"
      },
      {
        "color": "Red"
      }
    ]
  },
  {
    "brand": "Ford",
    "model": "Ranger",
    "colors": [
      {
        "color": "Blue"
      },
      {
        "color": "Grey"
      }
    ]
  },
  {
    "brand": "Peugeot",
    "model": "208 GTi",
    "colors": [
      {
        "color": "Blue"
      },
      {
        "color": "Grey"
      }
    ]
  }
]

@JamieMason
Copy link
Author

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 modified pluck that takes a path like pluck('child.grandChild.greatGrandChild') for example, but your data has an Array of colors 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 do pluck('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:

const colorSumsByName = {};

cars.forEach((car) => {
  car.colors.forEach(({ color: colorName }) => {
    colorSumsByName[colorName] = colorSumsByName[colorName] || 0;
    colorSumsByName[colorName] += 1;
  });
});

console.log(colorSumsByName);

Output

{ Black: 2, Blue: 3, Red: 1, Grey: 2 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment