-2

I have an array of country details:

var countryArr = [{"name":"Afghanistan","alpha2Code":"AF"},{"name":"Åland Islands","alpha2Code":"AX"},{"name":"Albania","alpha2Code":"AL"},{"name":"Algeria","alpha2Code":"DZ"},{"name":"American Samoa","alpha2Code":"AS"},{"name":"Andorra","alpha2Code":"AD"},{"name":"Angola","alpha2Code":"AO"}]

How can I get each value of the name attribute from this array? So I end up with an array of country names: ["Afghanistan", "Åland Islands"...]

ynwebdev
  • 11
  • 4
  • What have you tried so far to solve it on your own? This doesn't require more than a simple loop and an array for the names. – Andreas Dec 09 '19 at 16:11

1 Answers1

2

This is a job for Array.map!

const justTheNames = countryArr.map(country => country.name);

Explanation: The Array.map method will iterate through the elements of the array, applying the given callback function to each and returning a new array with the return values from the callback. In this case, it'll iterate over the array of country objects and create a new array with just the country names.

IceMetalPunk
  • 5,476
  • 3
  • 19
  • 26