That is to make this:
[ [\'dog\',\'cat\', [\'chicken\', \'bear\'] ],[\'mouse\',\'horse\'] ]
into:
[\'dog\',\'cat\',\'chicken\',\'
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()
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)
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 :)
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"]
Small fix for ChewOnThis_Trident solution and it works perfect:
Array.prototype.flatten = function() {
return this.reduce(function(a, b) {
return a.concat(b);
}, []);
};
Grab underscore.js and use the flatten function.
_.flatten([ ['dog','cat', ['chicken', 'bear'] ],['mouse','horse'] ]);