how to make array in array flat javascript recursive code example

Example 1: how to flatten nested arrays 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: flatten array object javascript

var flattenArray = function(data) {
	return data.reduce(function iter(r, a) {
		if (a === null) {
			return r;
		}
		if (Array.isArray(a)) {
			return a.reduce(iter, r);
		}
		if (typeof a === 'object') {
			return Object.keys(a).map(k => a[k]).reduce(iter, r);
		}
		return r.concat(a);
	}, []);
}
console.log(flattenArray(data))

//replace data with your array