Vardan Hambardzumyan
Vardan Hambardzumyan

Reputation: 416

mapping through the array of arrays ReactJS / JS

I have the following code.

I have this array of array data.

    const data = [
    [
      {
        city: "Phnom Penh",
        country: "KH"
      },
      {
        city: "Tirana",
        country: "AL"
      },
      {
        city: "Andorra la Vella",
        country: "AD"
      }
    ],
    [
      {
        city: "Mariehamn",
        country: "AX"
      }
    ],
    []
    ];

I am trying to print all city in the new variable and then want to show in select

    const cities = data.map((el) => el).map((el, idx) => el[idx]?.city);

      <select>
        {cities.map((el) =>  (
          <option value={el} key={idx}>
            {el}
          </option>)}
      </select>

But I am getting only first city.

The output now is

    (3) ["Phnom Penh", undefined, undefined]

But the output should be

    (4) ["Phnom Penh", "Tirana", "Andorra la Vella", "Mariehamn"]

Please help me to correct my code.

Thanks.

Upvotes: 0

Views: 444

Answers (3)

Asadbek Eshboev
Asadbek Eshboev

Reputation: 111

const cities = data.flat().map(item => item.city);

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

The Javascript map() method in JavaScript creates an array by calling a specific function on each element present in the parent array. It is a non-mutating method. Generally, the map() method is used to iterate over an array and calling function on every element of the array.

console.log(cities);
// Output: ["Phnom Penh", "Tirana", "Andorra la Vella", "Mariehamn"]

Upvotes: 1

Juljo Shahini
Juljo Shahini

Reputation: 148

Since flat may not be available on every environment I am providing with an alternative solution:

let cities = [];
data.forEach(el=> {
    el.forEach(element => {
    cities.push(element.city);
  });
});

Upvotes: 0

someone
someone

Reputation: 691

I fixed your code

For an easy way to understand what's going on, I divided it into two variables.

  const a = data.flatMap((num) => num);
  const b = a.map((el) => el.city);

And then you can show it in your select tag

Upvotes: 2

Related Questions