Is there an easy way to make nested array flat?

后端 未结 12 1472
执笔经年
执笔经年 2020-12-29 09:42

That is to make this:

[ [\'dog\',\'cat\', [\'chicken\', \'bear\'] ],[\'mouse\',\'horse\'] ]

into:

[\'dog\',\'cat\',\'chicken\',\'

相关标签:
12条回答
  • 2020-12-29 10:28

    I know this is late but I also ran into a situation where I needed to make a multidimensional array into 1 array and I made a function as follows.

    function nested(arr) {
        var noNest = arr.toString().split(',').filter(Boolean),
            i = 0;
    
        for(i;i<noNest.length; i++){
            if(isNaN(noNest[i])){
                return console.log(noNest);
            } else {
                noNest[i] = parseInt(noNest[i]);
            }
        }
        return console.log(noNest);
    }
    
    nested([[['a']], [['b']]]);
    

    This also take the nested arrays inside the tested array and makes sure its one array as the final out put

    0 讨论(0)
  • 2020-12-29 10:28

    That's why I love javascript:

    function flattenArray(source) {
      return source.toString().split(',');
    }
    
    flattenArray([['dog', 'cat', ['chicken', 'bear']], ['mouse', 'horse']]);
    // -> ['dog','cat','chicken','bear','mouse','horse']
    
    0 讨论(0)
  • 2020-12-29 10:31

    Assuming an array that's already unpacked from JSON, try this:

    Array.prototype.flatten = function() {
        var r = [];
        for (var i = 0; i < this.length; ++i) {
            var v = this[i];
            if (v instanceof Array) {
                Array.prototype.push.apply(this, v.flatten());
            } else {
                r.push(v);
            }
        }
        return r;
    };
    

    It appears to work correctly on your input - see http://jsfiddle.net/alnitak/Ws7L5/

    0 讨论(0)
  • 2020-12-29 10:35

    This solution has been working great for me, and i find it particularly easy to follow:

    function flattenArray(arr) {
      // the new flattened array
      var newArr = [];
    
      // recursive function
      function flatten(arr, newArr) {
        // go through array
        for (var i = 0; i < arr.length; i++) {
          // if element i of the current array is a non-array value push it
          if (Array.isArray(arr[i]) === false) {
            newArr.push(arr[i]);
          }
          // else the element is an array, so unwrap it
          else {
            flatten(arr[i], newArr);
          }
        }
      }
    
      flatten(arr, newArr);
    
      return newArr;
    }
    
    0 讨论(0)
  • 2020-12-29 10:40
    var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
      return a.concat(b);
    });
    // flattened is [0, 1, 2, 3, 4, 5]
    

    It's note worthy that reduce isn't supported in IE 8 and lower.

    developer.mozilla.org reference

    0 讨论(0)
  • 2020-12-29 10:40

    ES6 way of doing this would be

    [['a', 'b'], ['c', 'd']].reduce((x,v) => [...x, ...v], [])
    
    0 讨论(0)
提交回复
热议问题