zara esmaeili
zara esmaeili

Reputation: 11

How to map an array of arrays and just return it

I have an array of arrays, and I want to map over it and just return the values of arrays, but when I map over it and log the result, it's just an array and I don't know how to map over my array and use it in other places.

 const arr = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
  ];

  const arrMap = arr.map((it) => it.map((itm) => itm));
  console.log(arrMap);


//what I expected 1,2,3,4,5,6 , ...
//what I got [Array(3), Array(3), Array(3)]

Actually, I need the values for using them in somewhere else, but I don't know what to do. I also used function for this but when I return the values and log them It's undefined:

  const arr = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
  ];

  
  const arrMap = (arr) => {
    arr.forEach((element) => {
      console.log(element);
//In here, everything works fine
      return element;
    });
  };
  console.log(arrMap);

//what I got undefined

Upvotes: 1

Views: 4575

Answers (4)

William
William

Reputation: 132

forEach doesn't return anything it's like a for loop but for array only. Since you have double array you should flat it by using flatMap

  const arr = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
  ];
  const arrMap = arr.flatMap((it) => it);
  console.log(arrMap);

Upvotes: 0

MikeM
MikeM

Reputation: 13641

Use flat if you just want to flatten the array:

const arr = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

console.log(arr.flat());

Use flatMap if you want to do something with each element before the array gets flattened.

const arr = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

const arrMap = arr.flatMap((el) => {
  el.forEach((n) => console.log(n));
  return el;
});

console.log(arrMap);

Upvotes: 0

Tushar Shahi
Tushar Shahi

Reputation: 20676

Why it won't work : map() is supposed to run on each element of an array and return a transformed array of the same length. You have three elements in your input array and will always get three elements in your mapped array.

Your expectations can be met by tweaking your code with forEach() if you want. With forEach() there is nothing returned and you will have to start with a separate array variable. Below code uses ...

const arr = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
  ];

  let arrMap = [];
  arr.forEach((it) => arrMap.push(...it));
  console.log(arrMap);

But flatMap() is already there:

 const arr = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
  ];
  
  let ans = arr.flatMap(x => x);
  console.log(ans);

Upvotes: 0

Nikhil Patil
Nikhil Patil

Reputation: 2540

Use flatMap -

const arr = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

const arrMap = arr.flatMap(m => m);
console.log(arrMap);

Upvotes: 6

Related Questions