Pluck And Unique in JavaScript

Functional programming is most powerful when you combine a set of simple functions together in useful ways. For example, from some API you retrieve a list of vehicles:

var vehicles = [
  {name: 'mx-5', type: 'car', price: 20000},
  {name: 'ninja', type: 'motorcyle', price: 10000},
  {name: 'enzo', type: 'car', price: 1000000}
];

And you want to get the number of types:

var types = {};
vehicles.forEach(function(vehicle) {
    types[vehicle.type] = true;
});
var typeNumber = Object.keys(types).length;

console.log(typeNumber);// 2

That was somewhat cumbersome for such a simple operation. It would be even worse for < IE 9 as Object.keys would not exist. But by using pluck, which takes all values of a key in an array of object. And unique which removes duplicate values in an array, this is easy:

var typeNumber = unique(pluck(vehicles, 'type')).length;
console.log(typeNumber);// 2

The unique and pluck functions are just the vehicle type checking code abstracted and modularized:

var unique = function(arr) {
    var types = {};
    arr.forEach(function(element) {
        types[element] = true;
    });

    return Object.keys(types);
};

var pluck = function(arr, type) {
    var plucked = [];
    arr.forEach(function(element) {
        plucked.push(element[type]);
    });

    return plucked;
};

Similar functions are available in libraries like Lo-Dash, but I still think it is important to know how they work and why they exists.

Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2014/pluckAndUnique.js