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

StackOverflow https://stackoverflow.com/questions/23157185

  •  05-07-2023
  •  | 
  •  

Question

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","....."]
Was it helpful?

Solution 2

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

OTHER TIPS

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"]

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;
  };

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top