DEV Community

Aditya Singh
Aditya Singh

Posted on

Array flattening

💡 It is a process through which we can reduce the dimension of the array

  • We can use concat() method for flattening the array
let arr = [[1,2],[3,[4,9]],[5,6]];

let flattened= [].concat(...arr);
console.log(flattened); //[ 1, 2, 3, [ 4, 9 ], 5, 6 ]
Enter fullscreen mode Exit fullscreen mode
  • Use array.flat() method, here you have to give the depth level of the array

    for example: array.flat(2)

    let arr = [[1,2],[3,[4,9]],[5,6]];
    
    console.log(arr.flat(2)); //[ 1, 2, 3,  4, 9 , 5, 6 ]
    
  • We can also make our own custom flat function for an array with the help of recursion

let arr = [[1,2],[3,[4,9]],[5,6]];

function customFlat(arr, dept = 1){
    let result = [];
    arr.forEach((ar) => {
        if(Array.isArray(ar) && dept>0){
            result.push(...customFlat(ar, dept-1))
        } else result.push(ar)
    });
    return result;
}

console.log(customFlat(arr, 2));
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
ant_f_dev profile image
Anthony Fung

Cool tip!

Sometimes I have arrays of objects, where each object has a property that's also an array. In that scenario, I usually use flatMap

Collapse
 
adii profile image
Aditya Singh

Yes, we can also use that for the same