javascript

Lodash - Flatten an array to multi levels deep

To convert multi-dimensional array to one dimensional Array in lodash then you can use flattenDeep method of lodash library.

const arr = [10, [12, [15, 16]], [12, [30, [40]], 50]];
const result = _.flattenDeep(arr);

console.log(result);
// => [10,12,15,16,12,30,40,50]

_.flattenDeep Lodash

_.flattenDeep(Array)

Parameter description

Array: [Required] The array that you want to flatten to multi-levels.

Example Demo

Multi-dimensional Array to One Dimensional Array

const arr = [
    [20, 30, 40],
    [20, 30, 40, [20, 30, 40, [20, 30, 40]]],
    [20, 30, 40, [20, 30, 40], [20, 30, 40, [20, 30, 40]]]
];

const one_d_arr = _.flattenDeep(arr);
console.log(one_d_arr);

Live Demo

Was this helpful?