Search code examples
javascriptmultidimensional-arrayconcatenation

How do I flatten a two-dimensional array with 3 entries in javascript?


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.


Solution

  • 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]
    ]));