That is to make this:
[ [\'dog\',\'cat\', [\'chicken\', \'bear\'] ],[\'mouse\',\'horse\'] ]
into:
[\'dog\',\'cat\',\'chicken\',\'
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
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']
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/
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;
}
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
ES6 way of doing this would be
[['a', 'b'], ['c', 'd']].reduce((x,v) => [...x, ...v], [])