convert nested arra y t o a single array in js code example

Example 1: flatten nested array javascript

// using recursion, .reduce() and .concat() methods
// works with arrays of any depth

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);

/*
	Output: [ 1, 2, 3, 4, 5 ]
*/

Example 2: Javascript flatten array of arrays

var multiDimensionArray = [["a"],["b","c"],["d"]]; //array of arrays
var flatArray = Array.prototype.concat.apply([], multiDimensionArray); //flatten array of arrays
console.log(flatArray); // [ "a","b","c","d"];