0

I have an array with different objects inside. I want to write a function pluck which takes the array & a property and return an array of all the values of that property in the different objects.

I have tried this:

var paints = [
    {color: 'red'},
    {color: 'yellow'},
    {color: 'blue'},
];

function pluck(arr, property) {
    return arr.map(function(obj, property) {
        return obj[property];
    });

}
console.log(pluck(paints, 'color'));

This does not work.

If I change the function like so:

function pluck(arr) {
    return arr.map(function(obj) {
        return obj['color'];
    });

...it works, but it is obviously hard-coded now. However, I would like to call the function and specify which property I want to have returned in an array.

user74843
  • 701
  • 2
  • 10
  • 28

1 Answers1

1

So very close.

function pluck(arr, property) {
    return arr.map(function(obj) {
        return obj[property];
    });
}

You didnt need the property argument in the inner function, and by having it you redefined the one you're passing in to be something else.

var paints = [
    {color: 'red'},
    {color: 'yellow'},
    {color: 'blue'},
];

function pluck(arr, property) {
    return arr.map(function(obj) {
        return obj[property];
    });

}
console.log(pluck(paints, 'color'));
Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • The concept is called [`[Variable] Shadowing`](https://en.wikipedia.org/wiki/Variable_shadowing) – mhodges May 17 '17 at 15:32