如何将深度多维数组转换为单维数组 - Javascript

时间:2014-04-18 15:26:15

标签: javascript flatten

我有一个巨大的多维数组,我想转换成一个单维数组,真正的问题是数组是动态的,它可以是一个很深的,因为它想要的,我不能提前确定它。在这里发布一个例子

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

它应该转换为像

这样的单维数组
["hello","berries","grouped",88,"frozen","stuff","....."]

4 个答案:

答案 0 :(得分:5)

试试:

var flat = myArray.join().split(',');

输出:

["hello", "berries", "grouped", "88", "frozen", "stuff", "mash", "melon", "freeze", "12", "together", "people", "car", "orange", "code", "84", "mate", "women", "man", "bus", "car", "345", "lorry", "world"]

答案 1 :(得分:4)

你可以写一个助行器功能:

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

然后使用它来构建最终数组:

var final = [];
walkLeaves(arr, function(item, index) {
    final.push(item);
});

Demo

答案 2 :(得分:1)

不是纯JavaScript解决方案,但您可以使用underscore.js

_.flatten(myArray)

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

答案 3 :(得分:0)

正常循环+递归:

var flattened = [];
function flatten(a){
    a.forEach(function(e){
       if(toString.call(e) === "[object Array]") flatten(e);
       else flattened.push(e);
    });
}

flatten(myArray);