Flatten A Jagged Multi Dimensional Array
I need help flattening an array like this: [1,2,[2,3],[5,[6,1],4],7] I want it to be something like [1,2,2,3,5,6,1,4,7]. I have searched something like this, and found [].concat
Solution 1:
My recommendation would be to take a dependency on lodash and use the flattenDeep
function.
_.flattenDeep([1,2,[2,3],[5,[6,1],4],7])
// [ 1, 2, 2, 3, 5, 6, 1, 4, 7 ]
If you want to write your own function, you might want to peek at the lodash implementation.
In pseudo-code, here's a recursive approach:
result= []
function flatten(array)
foreach element inarray
if element isarray
flatten(element)
else
result.append(element)
EDIT
Here's a "by-hand" approach, though I'd definitely recommend relying on the better-tested lodash implementation.
functionflatten(arr, result) {
if (result === undefined) {
result = [];
}
for (var i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
flatten(arr[i], result);
} else {
result.push(arr[i]);
}
}
return result;
}
console.log(flatten([1, 2, [2, 3], [5, [6, 1], 4], 7]));
// Output:// [ 1, 2, 2, 3, 5, 6, 1, 4, 7 ]
Solution 2:
You can wrap the concat.apply
thing in a loop to handle deeply nested arrays:
while (a.some(Array.isArray))
a = [].concat.apply([], a)
or in the ES6 syntax:
while (a.some(Array.isArray))
a = [].concat(...a);
Post a Comment for "Flatten A Jagged Multi Dimensional Array"