I'd like to make an array of strings of the names

function namesOnly(arr) {

}
namesOnly([
  {
    name: "Angelina Jolie",
    age: 80
  },
  {
    name: "Eric Jones",
    age: 2
  },
  {
    name: "Paris Hilton",
    age: 5
  },
  {
    name: "Kayne West",
    age: 16
  },
  {
    name: "Bob Ziroll",
    age: 100
  }
])
// expect: ["Angelina Jolie", "Eric Jones", "Paris Hilton", "Kayne West", "Bob Ziroll"]

So hope!

3 Answers

1
Mamun On

Try with Array​.prototype​.map()

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

function namesOnly(arr) {
  return arr.map(i => i.name);
}
var res = namesOnly([
  {
    name: "Angelina Jolie",
    age: 80
  },
  {
    name: "Eric Jones",
    age: 2
  },
  {
    name: "Paris Hilton",
    age: 5
  },
  {
    name: "Kayne West",
    age: 16
  },
  {
    name: "Bob Ziroll",
    age: 100
  }
])
console.log(res);

Though I think map() is better fit here, you can also use for...of loop:

function namesOnly(arr) {
  var names = [];
  for (let o of arr) 
    names.push(o.name);
  return names;
}
var res = namesOnly([
  {
    name: "Angelina Jolie",
    age: 80
  },
  {
    name: "Eric Jones",
    age: 2
  },
  {
    name: "Paris Hilton",
    age: 5
  },
  {
    name: "Kayne West",
    age: 16
  },
  {
    name: "Bob Ziroll",
    age: 100
  }
])
console.log(res);

-1
Dillan Wilding On

You could use Array.map to compose a new array.

function namesOnly(arr) {
  return arr.map(element => { return element.name; });
}
0
Hien Nguyen On

You can use forEach and push to create your result

 function namesOnly(arr) {
       var result = [];
       arr.forEach(c=> { result.push(c.name); });

       console.log(result);
       return result;
    }

function namesOnly(arr) {
   var result = [];
   arr.forEach(c=> { result.push(c.name); });
   
   console.log(result);
   return result;
}

namesOnly([
  {
    name: "Angelina Jolie",
    age: 80
  },
  {
    name: "Eric Jones",
    age: 2
  },
  {
    name: "Paris Hilton",
    age: 5
  },
  {
    name: "Kayne West",
    age: 16
  },
  {
    name: "Bob Ziroll",
    age: 100
  }
])