1

I wants to reverse the array with sub arrays with nested loops. I do not wants to use the reverse function. But every-time I do that I get this a type-error.
anyways here is my code

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


for(let i = arr.length - 1; i > 0; i--)
  {
    for (let j = arr[i].lenght - 1; j > 0; j--)
      {
        console.log(arr[i][j]);
      }
  }

The result should be 9,8,7,6,5,4,3,2,1 but instead I get nothing blank.

user218592
  • 35
  • 4

2 Answers2

2

You had a typo in the word length and also it should be >= 0

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


for(let i = arr.length - 1; i >= 0; i--) {
    for (let j = arr[i].length - 1; j >= 0; j--) {
        console.log(arr[i][j]);
    }
}
User456
  • 1,216
  • 4
  • 15
  • turns out I do not have write [i] with it. the rest are the same. – user218592 Jun 20 '22 at 15:00
  • It works for me and in my opinion it is the best solution for this question because it shows how to display each value in subarrays with a **nested loop**. – Sofiane R Feb 12 '23 at 14:48
2

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

let result = arr
  .reduce((prev, current) => {
    return [...prev, ...current];
  }, [])
  .reduce((prev, current) => {
    return [current, ...prev];
  }, []);

console.log("result is", result);

You can use this also, using reduce let me know if it works for you or not

DanteDX
  • 1,059
  • 7
  • 12