Search code examples
javascriptnested-loopssub-array

reversing sub arrays with nested loop Javascript


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.


Solution

  • 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