-2

The output of the following snippet should return the names of 5 cities in an array, but the result is a blank array. Why?

arr = [
  {name: "London", population: 30},
  {name: "Moscow", population: 20},
  {name: "Delhi", population: 50},
  {name: "New York", population: 35},
  {name: "Paris", population: 42}
]

var temp = [];
arr.forEach((item, index) => {
  temp.push[item.name];
});
console.log(temp);
Deadpool
  • 7,811
  • 9
  • 44
  • 88

2 Answers2

2

use push(), not push[].

arr = [
  {name: "London", population: 30},
  {name: "Moscow", population: 20},
  {name: "Delhi", population: 50},
  {name: "New York", population: 35},
  {name: "Paris", population: 42}
]

var temp = [];
arr.forEach((item, index) => {
  temp.push(item.name);
});
console.log(temp);
Kristian
  • 2,456
  • 8
  • 23
  • 23
2

push is a array method but you are using that as if it is an object having property item.name. Instead of [] use () to invoke/call the method:

var arr = [
  {name: "London", population: 30},
  {name: "Moscow", population: 20},
  {name: "Delhi", population: 50},
  {name: "New York", population: 35},
  {name: "Paris", population: 42}
]

var temp = [];
arr.forEach((item, index) => {
  temp.push(item.name);
});

console.log(temp);

You can also try with Array.prototype.map() which is much easier and cleaner:

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

var arr = [
  {name: "London", population: 30},
  {name: "Moscow", population: 20},
  {name: "Delhi", population: 50},
  {name: "New York", population: 35},
  {name: "Paris", population: 42}
]

var temp = arr.map(i => i.name);
console.log(temp);
Mamun
  • 66,969
  • 9
  • 47
  • 59