home

Flattern nested array

Word count icon

29 words

Reading time icon

1 minutes

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

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

With flat()

The second uses the new flat() method.

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

With depth

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