Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
155
rated 0 times [  161] [ 6]  / answers: 1 / hits: 134115  / 10 Years ago, wed, december 3, 2014, 12:00:00

As we know, to flatten the array [[0, 1], [2, 3], [4, 5]] by using the method reduce()



var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
return a.concat(b);
});


So how to flatten this array [[[0], [1]], [[2], [3]], [[4], [5]]] to [0, 1, 2, 3, 4, 5]?


More From » arrays

 Answers
52

This is an alternative to recursion (see jsfiddle here) and should accept any level of depth which avoids stack overflow.





var array = [[0, 1], [2, 3], [4, 5, [6, 7, [8, [9, 10]]]]];
console.log(flatten(array), array); // does not mutate array
console.log(flatten(array, true), array); // array is now empty

// This is done in a linear time O(n) without recursion
// memory complexity is O(1) or O(n) if mutable param is set to false
function flatten(array, mutable) {
var toString = Object.prototype.toString;
var arrayTypeStr = '[object Array]';

var result = [];
var nodes = (mutable && array) || array.slice();
var node;

if (!array.length) {
return result;
}

node = nodes.pop();

do {
if (toString.call(node) === arrayTypeStr) {
nodes.push.apply(nodes, node);
} else {
result.push(node);
}
} while (nodes.length && (node = nodes.pop()) !== undefined);

result.reverse(); // we reverse result to restore the original order
return result;
}




[#68608] Monday, December 1, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
austynp

Total Points: 505
Total Questions: 118
Total Answers: 106

Location: Tajikistan
Member since Sun, Aug 29, 2021
3 Years ago
austynp questions
;