22

Does anyone know of a 'pluck' plugin that matches the underscore array method?

pluck_.pluck(list, propertyName) 

A convenient version of what is perhaps the most common use-case for map: extracting a list of property values.

var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}];
_.pluck(stooges, 'name');
=> ["moe", "larry", "curly"]

Google is not helping me much today. Any pointers much appreciated

daryal
  • 14,643
  • 4
  • 38
  • 54
Chin
  • 12,582
  • 38
  • 102
  • 152

4 Answers4

32

You can do it with an expression;

var arr = $.map(stooges, function(o) { return o["name"]; })
Alex K.
  • 171,639
  • 30
  • 264
  • 288
  • 2
    I was about to use the above solution, but then realized in testing that it is different from _.pluck in some edge cases. If the 'name' property as used above is null or undefined in any object in the array, this function will just omit that element from the arr output entirely, leaving a smaller array than one began with. The following covers this: var arr = []; $.each(stooges, function(i,o) { return arr.push(o["name"]); }); – Julie Aug 14 '14 at 20:35
22

just write your own

$.pluck = function(arr, key) { 
    return $.map(arr, function(e) { return e[key]; }) 
}
Otto Allmendinger
  • 27,448
  • 7
  • 68
  • 79
9

It's quite simple to implement this functionality yourself:

function pluck(originalArr, prop) {
    var newArr = [];
    for(var i = 0; i < originalArr.length; i++) {
        newArr[i] = originalArr[i][prop];
    }
    return newArr;
}

All it does is iterate over the elements of the original array (each of which is an object), get the property you specify from that object, and place it in a new array.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
1

In simple case:

var arr = stooges.map(function(v) { return v.name; });

More generalized:

function pluck(list, propertyName) {
    return list.map(function (v) { return v[propertyName]; })
}

But, IMHO, you should not implement it as tool function, but use the simple case always.

2018 update:

var arr = stooges.map(({ name }) => name);
micha_s
  • 73
  • 7