0

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.

3

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

flatMap internally does a map and a flat and the map step seems unnecessary in this case. therefore a flat is enough
1
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"]

Comments

0

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);
  });
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.