how to flatten a nested array javascript code example
Example 1: 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);
Example 2: flatten an array javascript
var arrays = [
["$6"],
["$12"],
["$25"],
["$25"],
["$18"],
["$22"],
["$10"]
];
var merged = [].concat.apply([], arrays);
console.log(merged);
Example 3: 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))