Home > other >  mapping through the array of arrays ReactJS / JS
mapping through the array of arrays ReactJS / JS

Time:12-27

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.

CodePudding user response:

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

CodePudding user response:

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"]

CodePudding user response:

To get the desired output, you can use the flatMap() method to flatten the array and then map over the resulting array to extract the city names. Here is how you can do this:

const cities = data.flatMap((el) => el).map((el) => el.city);

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

The flatMap() method flattens the array by concatenating the inner arrays and then applying the mapping function to each element. In this case, the mapping function extracts the city property from each element and returns it as a new array.

CodePudding user response:

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