Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a deep multi dimensional array to a single dimensional array - Javascript

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","....."]
like image 765
Aman Virk Avatar asked Jan 23 '26 02:01

Aman Virk


2 Answers

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"]
like image 65
hsz Avatar answered Jan 25 '26 14:01

hsz


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

like image 24
Ja͢ck Avatar answered Jan 25 '26 14:01

Ja͢ck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!