how to flatten nested arrays code example
Example 1: javascript array flatten
const arr1 = [1, 2, [3, 4]];
arr1.flat();
const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
const arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
Example 2: flatten nested array javascript
function flatten(arr)
{
return arr.reduce((acc, cur) => acc.concat(Array.isArray(cur) ? flatten(cur) : cur), []);
};
const arr = [[1,2],[3,[4,[5]]]];
const flattened = flatten(arr);
console.log(flattened);