justask.dev

Community powered answers to your dev questions

Flattern nested array

posted: 2019 December 5th

category: javascript

Edit this post on GitHub.

Back

Two ways to flattern a nested array. he first is the more traditional approach using reduce and concat.

1const myArray = [['1', '2', '3'], ['4', '5']];
2
3const flatArray = myArray.reduce((total, amount) => total.concat(amount));
4
5>> ['1', '2', '3', '4', '5']

The second uses the new flat() method. As an argument you can pass in the depth - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat

1const nestedArray = [1, 2, [3, 4]].flat();
2nestedArray.flat();
3>> [1, 2, 3, 4]

With depth

1var nestedArray = [1, 2, [3, 4, [5, 6]]];
2nestedArray.flat(2);
3>> [1, 2, 3, 4, 5, 6]

Author: Rich Haines