我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
当前回答
我认为最好的方法是这样:
var flatten = function () {
return [].slice.call(arguments).toString().split(',');
};
其他回答
这是我的版本。它允许您将复杂的对象展平,可以在更多场景中使用:
输入
var input = {
a: 'asdf',
b: [1,2,3],
c: [[1,2],[3,4]],
d: {subA: [1,2]}
}
Code
功能如下:
function flatten (input, output) {
if (isArray(input)) {
for(var index = 0, length = input.length; index < length; index++){
flatten(input[index], output);
}
}
else if (isObject(input)) {
for(var item in input){
if(input.hasOwnProperty(item)){
flatten(input[item], output);
}
}
}
else {
return output.push(input);
}
};
function isArray(obj) {
return Array.isArray(obj) || obj.toString() === '[object Array]';
}
function isObject(obj) {
return obj === Object(obj);
}
用法
var output = []
flatten(input, output);
输出
[“asdf”,1,2,3,1,2,3,4,1,2]
如何使用JavaScript 1.8的reduce(callback[,initialValue])方法
list.reduce((p,n) => p.concat(n),[]);
能胜任这项工作。
我最初想使用.reduce方法并递归调用一个函数来展平内部数组,但是当使用深度嵌套数组的深度嵌套数组时,这可能会导致堆栈溢出。使用concat也不是最好的方法,因为每次迭代都会创建数组的新浅层副本。我们可以做的是:
const flatten = arr => {
for(let i = 0; i < arr.length;) {
const val = arr[i];
if(Array.isArray(val)) {
arr.splice(i, 1, ...val);
} else {
i ++;
}
}
return arr;
}
我们没有通过concat创建新数组,也没有递归调用任何函数。
http://jsbin.com/firiru/4/edit?js安慰
有一种比使用上面的答案中列出的merge.contat.apply()方法快得多的方法来实现这一点,我的意思是速度快几个数量级。这假设您的环境可以访问ES5 Array方法。
var array2d = [
["foo", "bar"],
["baz", "biz"]
];
merged = array2d.reduce(function(prev, next) {
return prev.concat(next);
});
这里是jsperf链接:http://jsperf.com/2-dimensional-array-merge
您可以使用Undercore:
var x = [[1], [2], [3, 4]];
_.flatten(x); // => [1, 2, 3, 4]