Ecma262: Normative: Array.prototype.pluck

Created on 10 Oct 2018  路  5Comments  路  Source: tc39/ecma262

Note: I only have about a 1.5 years of professional dev experience, and am not well versed in how this sort of thing goes. Please be patient with me.

Assume we have an array of objects that are of the same schema (for lack of a better term), and wish to quickly fetch values on certain keys, pluck would allow us to do so.

Example data:

let arrOfObjs = [
    {
        firstName: 'John',
        lastName: 'Smith',
        cellNum: '(441)-1**-****'
    },
    {
        firstName: 'Foo',
        lastName: 'Bar',
        cellNum: '(144)-1**-****'
    },
    {
        firstName: 'Sarah',
        lastName: 'Smith',
        cellNum: '(251)-1**-****'
    },
] ;

Previous solution:

let firstNames = arrOfObjs.map( function (obj) { return obj.firstName} )

console.log(firstNames); // ['John', 'Foo', 'Sarah']

New solution (with Array.prototype.pluck):

let firstNames = arrOfObjs.pluck('firstName');

console.log(firstNames); // ['John', 'Foo', 'Sarah']

We could also make this variadic, plucking only the values we need. Although this could be done with destructing in Array.prototype.map, I think it would be convenient to have pluck instead.

let justNames = arrOfObjs.pluck('firstName', 'lastName');

console.log(justNames);
/*
[
    {
        firstName: 'John',
        lastName: 'Smith',
    },
    {
        firstName: 'Foo',
        lastName: 'Bar',
    },
    {
        firstName: 'Sarah',
        lastName: 'Smith',
    },
] 
*/

Also, php supports this in the form of array_column, but it's not variadic.

feature suggestion

Most helpful comment

This isn't the place to propose features, see https://github.com/tc39/ecma262/blob/master/CONTRIBUTING.md#new-feature-proposals.

All 5 comments

This isn't the place to propose features, see https://github.com/tc39/ecma262/blob/master/CONTRIBUTING.md#new-feature-proposals.

Ah okay, thanks! Also, at the risk of sounding like a total noob, do you think this is worth going through the process? I don't want to go through the whole process if it's plainly obvious that this isn't necessary.

Given that you can also write your example as arr.map(obj => obj.firstName) if I'm not mistaken, I somewhat doubt it folks will be convinced it's worth adding another method for, but who knows. Asking on the mailing list or IRC will give you an idea.

In addition to CONTRIBUTING.md, I'd recommend starting with making a library which does this, and gathering broad developer feedback, before proposing for standardization.

Note that Lodash used to have _.pluck, but later removed it in favor of _.map with iteratee shorthand analogous to @annevk's counter-example.

Was this page helpful?
0 / 5 - 0 ratings