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.