Reputation: 3977
I have a huge multi-dimensional array that i want to convert into a single dimensional array, the real issue is the array is dynamic and it can be a deep as it want to be and i am not sure about it in advance. Posting an example here
var myArray = [
"hello",
["berries", "grouped", 88, "frozen"],
[
"stuff",
[
"mash",
["melon", "freeze", 12, "together"],
"people"
],
"car"
],
[
"orange",
"code",
84,
["mate", "women", "man"]
],
["bus", "car", 345, "lorry"],
"world"
];
It should be converted to a single dimensional array like
["hello","berries","grouped",88,"frozen","stuff","....."]
Upvotes: 2
Views: 101
Reputation: 18018
Normal looping + recursion:
var flattened = [];
function flatten(a){
a.forEach(function(e){
if(toString.call(e) === "[object Array]") flatten(e);
else flattened.push(e);
});
}
flatten(myArray);
Upvotes: 0
Reputation: 173622
You can write a walker function:
function walkLeaves(arr, fn)
{
for (var i = 0; i < arr.length; ++i) {
if (typeof arr[i] == 'object' && arr[i].length) { // simple array check
walkLeaves(arr[i], fn);
} else {
fn(arr[i], i); // only collect leaves
}
}
}
And then use that to build the final array:
var final = [];
walkLeaves(arr, function(item, index) {
final.push(item);
});
Upvotes: 4
Reputation: 74685
Not a pure JavaScript solution but you could use underscore.js:
_.flatten(myArray)
...and this is how they do it:
var flatten = function(input, shallow, output) {
if (shallow && _.every(input, _.isArray)) {
return concat.apply(output, input);
}
each(input, function(value) {
if (_.isArray(value) || _.isArguments(value)) {
shallow ? push.apply(output, value) : flatten(value, shallow, output);
} else {
output.push(value);
}
});
return output;
};
Upvotes: 1
Reputation: 152266
Just try with:
var flat = myArray.join().split(',');
Output:
["hello", "berries", "grouped", "88", "frozen", "stuff", "mash", "melon", "freeze", "12", "together", "people", "car", "orange", "code", "84", "mate", "women", "man", "bus", "car", "345", "lorry", "world"]
Upvotes: 5