Chrome Extension

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]
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

_.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

Search Index Data (The code snippet can also be found with below search text)

_.flattenDeep lodash
Was this helpful?
0 Comments
Join Devsheet Ask a Question