How to convert a 2D array to a 1D array in JavaScript

2 Answers

0 votes
function arr2DTo1D(arr2d) {
    const arr = new Array(arr2d.length * arr2d[0].length);
    let k = 0;
    
    for (let i = 0; i < arr2d.length; i++) {
        for (let j = 0; j < arr2d[i].length; j++) {
            arr[k++] = arr2d[i][j];
        }
    }
    
    return arr;
}

const arr2d = [ 
    [ 5, 6, 1, 4 ], 
    [ 3, 8, 0, 2 ],
    [ 9, 2, 7, 3 ] 
];

const arr = arr2DTo1D(arr2d);

arr.forEach(n => {
    process.stdout.write(n + "\t");
});

 
 
  
/*
run
 
5	6	1	4	3	8	0	2	9	2	7	3	
  
*/


 



answered Aug 14, 2024 by avibootz
0 votes
const arr2d = [ 
    [ 5, 6, 1, 4 ], 
    [ 3, 8, 0, 2 ],
    [ 9, 2, 7, 3 ] 
];

const arr = arr2d.flat();

arr.forEach(n => {
    process.stdout.write(n + "\t");
});

 
  
/*
run
 
5	6	1	4	3	8	0	2	9	2	7	3	
  
*/

 



answered Aug 14, 2024 by avibootz

Related questions

1 answer 186 views
1 answer 189 views
2 answers 247 views
1 answer 188 views
1 answer 179 views
1 answer 200 views
...