0

As the title states, I am trying to return an array containing the value associated with that key for each object, or undefined if that key is not present.

Here is what I have so far:

function pluck(arr, name) {

permittedValues = arr.map(function(value) {
  return value.key || undefined;
});
}
console.log(
  pluck([
  { name: "Tim" }, { name: "Matt" }, { name: "Elie" }],
 'name'
)
  );

I am trying to return something like this:

// ["Tim", "Matt", "Elie"]
Cody Wirth
  • 71
  • 1
  • 5

2 Answers2

2

You can use indexer to get the property and if it doesn't exist, undefined will be returned:

function pluck(arr, name) {
    return arr.map(function (value) {
        return value[name];
    });
}
Shahzad
  • 2,033
  • 1
  • 16
  • 23
1

You don't need to return value[name] || undefined, if name key doesn't exist it will return undefined anyway.

function pluck(arr, name) {

return permittedValues = arr.map(value => 
  value[name]);
}
console.log(
  pluck([
  { name: "Tim" }, { name: "Matt" }, { name: "Elie" }],
 'name'
)
  );

This code can get even more concise using arrow functions

const pluck = (arr, name) => arr.map(value => value[name])

console.log(pluck([{ name: "Tim" }, { name: "Matt" }, { name: "Elie" }],'name'));
kooskoos
  • 4,622
  • 1
  • 12
  • 29