-1

I was asked to write a function 'flat' that flattens a 2-dimensional array with 3 entries. The function should return an array with 9 elements.

For example, console.log (flat([[1,2,3], [5,7,8], [9,4,6]])) should return [1,2,3,5,7,8,9,4,6]

My code is like this:

  function flat(arr){
     
        let newArr = [];

        for (var i =0; i< 3; i++){

            for (var j = 0; j< 3; j++){

                return newArr.concat(arr[i][j]);
            }
        }

   }

   console.log (flat([[1,2,3], [5,7,8], [9,4,6]]));   

With this code, I only have the first element, [1], returned in the array newArr. Can anyone help with this problem? Or is there any other way to flatten a 2D array? Thanks.

2 Answers2

1

You can use the built in array method .flat() to do this.

In your example

function flat(array) {
    return array.flat()
}

Snippet

function flat(arr) {
  return arr.flat()
}

console.log(flat([
  [1, 2, 3],
  [5, 7, 8],
  [9, 4, 6]
]));
lejlun
  • 4,140
  • 2
  • 15
  • 31
-1

function flat(arr){
  let newArr = [];
  for (var i =0; i< 3; i++){
      for (var j = 0; j< 3; j++){
          newArr.push(arr[i][j]);
      }
  }
  return newArr;
}

console.log (flat([[1,2,3], [5,7,8], [9,4,6]]));   

You need to move the return statement out of the loop, or else it will exit the function the first time it gets to that line.

StardustGogeta
  • 3,331
  • 2
  • 18
  • 32