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","....."]
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"]
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);
});
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With