Equivalent of Underscore _.pluck in pure JavaScript Equivalent of Underscore _.pluck in pure JavaScript arrays arrays

Equivalent of Underscore _.pluck in pure JavaScript


In ES5:

function pluck(array, key) {  return array.map(function(obj) {    return obj[key];  });}

In ES6:

function pluck(array, key) {  return array.map(o => o[key]);}


You can do it with the native JavaScript .map():

Array.prototype.pluck = function(key) {  return this.map(function(object) { return object[key]; });};

edit — modifying built-in prototype objects should be done with care; a better way to add the function (should you be OK with the idea of doing so in general) would be with Object.defineProperty so that it can be made non-enumerable:

Object.defineProperty(Array.prototype, "pluck", {    value: function(key) {        return this.map(function(object) { return object[key]; });    }});


You are so close. You need to change:

newArr.push(arr[i].key);

to:

newArr.push(arr[i][key]);

Consider this:

var obj = { myKey: 'my Value', theKey: 'another value' };var theKey = 'myKey';alert(obj.theKey); // another valuealert(obj[theKey]); // my Value// You can also send in strings here:alert(obj['theKey']); // another value

Hope you get my point.