将这个:
[ ['dog','cat', ['chicken', 'bear'] ],['mouse','horse'] ]
转换成:
['dog','cat','chicken','bear','mouse','horse']
将这个:
[ ['dog','cat', ['chicken', 'bear'] ],['mouse','horse'] ]
转换成:
['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]
值得注意的是,在IE 8及更低版本中不支持reduce方法。
在现代浏览器中,您可以只用几行代码而不需要任何外部库来实现此功能:
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"]
下载underscore.js并使用flatten函数。
_.flatten([ ['dog','cat', ['chicken', 'bear'] ],['mouse','horse'] ]);
console.log([['dog', 'cat', ['chicken', 'bear']], [['mouse', 'horse'], 'lion']].join().split(','));
基本上,join方法可以从嵌套的数组中生成逗号分隔的字符串。使用split方法可以获取一维数组。很不错吧?额外奖励它也可以在所有主流浏览器上运行 :)
对 ChewOnThis_Trident 的解决方案进行小修补,现在它完美运作:
Array.prototype.flatten = function() {
return this.reduce(function(a, b) {
return a.concat(b);
}, []);
};
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;
};
看起来它在你的输入上运行正常 - 请参阅http://jsfiddle.net/alnitak/Ws7L5/
现在在2019年,您可以轻松地使用 Array.flat
以任意深度。
let arr = [ ['dog','cat', ['chicken', 'bear'] ],['mouse','horse'] ]
let op = arr.flat(Infinity)
console.log(op)
如果您想获取唯一的值,可以将Set和flat结合使用。
let arr = [ ['dog','cat', ['chicken', 'bear', 'cat'] ],['mouse','horse', 'dog'], [[[['deeper','chicken']]]] ]
let unique = [...new Set(arr.flat(Infinity))]
console.log(unique)
我知道现在有点晚了,但我也遇到了需要将多维数组转换为一维数组的情况,我写了一个函数如下。
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']]]);
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 arr = [['dog','cat', ['chicken', 'bear']],[['mouse','horse'],'lion'] ];
var flattened = arr.flat(Infinity);
//output--> ["dog", "cat", "chicken", "bear", "mouse", "horse", "lion"]
[
和]
,然后添加一个开头和结尾的括号。 - pimvdb