开发者

Is there an easy way to make nested array flat?

That is to make this:

[ ['dog','cat', ['chicken', 'b开发者_运维知识库ear'] ],['mouse','horse'] ]

into:

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


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


In modern browsers you can do this without any external libraries in a few lines:

Array.prototype.flatten = function() {
  return this.reduce(function(prev, cur) {
    var more = [].concat(cur).some(Array.isArray);
    return prev.concat(more ? cur.flatten() : cur);
  },[]);
};

console.log([['dog','cat',['chicken', 'bear']],['mouse','horse']].flatten());
//^ ["dog", "cat", "chicken", "bear", "mouse", "horse"]


Grab underscore.js and use the flatten function.

_.flatten([ ['dog','cat', ['chicken', 'bear'] ],['mouse','horse'] ]);


What about this one liner code ?

console.log([['dog', 'cat', ['chicken', 'bear']], [['mouse', 'horse'], 'lion']].join().split(','));

basically join will make comma separated string from nested array and using split you can get 1d array, nice ? bonus it'll work on all major browsers as well :)


Small fix for ChewOnThis_Trident solution and it works perfect:

Array.prototype.flatten = function() {
    return this.reduce(function(a, b) {
        return a.concat(b);
    }, []);
};


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/


Now in 2019 you can easily use Array.flat with whatever depth you want.

let arr  = [ ['dog','cat', ['chicken', 'bear'] ],['mouse','horse'] ]

let op = arr.flat(Infinity)

console.log(op)

Now if you want to get unique values you can combine both Set and flat

let arr  = [ ['dog','cat', ['chicken', 'bear', 'cat'] ],['mouse','horse', 'dog'], [[[['deeper','chicken']]]] ]

let unique  = [...new Set(arr.flat(Infinity))]

console.log(unique)
Browser comparability Except IE all other seems to support for IE you can use polyfill.


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


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


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


The easiest way of flattening the Objects of any depth would be using the flat method

var arr = [['dog','cat', ['chicken', 'bear']],[['mouse','horse'],'lion'] ]; 
var flattened = arr.flat(Infinity);
//output--> ["dog", "cat", "chicken", "bear", "mouse", "horse", "lion"]

More aout Flat()


ES6 way of doing this would be

[['a', 'b'], ['c', 'd']].reduce((x,v) => [...x, ...v], [])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜