简体   繁体   English

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

[英]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","....."]

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: 你可以编写一个walker函数:

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 演示

Not a pure JavaScript solution but you could use underscore.js : 不是纯JavaScript解决方案,但您可以使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM