我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
当前回答
您可以使用array.prototype.reduce()和array.protocol.contat()展平数组
var data=[[“$6”],[“$12”],【“$25”】,[“$25“],【”$18”】,【”$22“】,【“$10”】,“$15”】、【”$3“】,[”$75“],[”$5“],“$100”]、【”$7“】、【“$3”】、“$75”],“$5”]]。reduce(函数(a,b){返回a.concat(b);}, []);console.log(数据);
相关文档:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/concat
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
其他回答
您可以使用“join()”和“split()”:
设arrs=[["$6"],["$12"],["$25"],["$25"],["$18"],["$22"],["$10"]];让newArr=arrs.join(“,”).split(“,“);console.log(newArr);//["$6", "$12", "$25", "$25", "$18", "$22", "$10"]
此外,还可以使用“toString()”和“split()”:
设arrs=[["$6"],["$12"],["$25"],["$25"],["$18"],["$22"],["$10"]];让newArr=arrs.toString().split(“,”);console.log(newArr);//["$6", "$12", "$25", "$25", "$18", "$22", "$10"]
然而,如果字符串包含逗号,上述两种方式都不能正常工作:
“join()”和“split()”:
设arrs=[["$,6"],["$,12"],["$2,5"],["$2,5"],[",$18"],["$22,"],["$,1,0"]];让newArr=arrs.join(“,”).split(“,“);console.log(newArr);// ["$", "6", "$", "12", "$2", "5", "$2", "5", "", "$18", "$22", "", "$", "1", "0"]
“toString()”和“split()”:
设arrs=[["$,6"],["$,12"],["$2,5"],["$2,5"],[",$18"],["$22,"],["$,1,0"]];让newArr=arrs.toString().split(“,”);console.log(newArr);// ["$", "6", "$", "12", "$2", "5", "$2", "5", "", "$18", "$22", "", "$", "1", "0"]
ES6的纯粹魔力
const flat = A => A.reduce((A, a) => Array.isArray(a) ? [...A, ...flat(a)] : [...A, a], []);
如果你使用lodash,你可以使用它的flatten方法:https://lodash.com/docs/4.17.14#flatten
lodash的优点是它还具有使数组变平的方法:
i) 递归地:https://lodash.com/docs/4.17.14#flattenDeep
ii)多达n层嵌套:https://lodash.com/docs/4.17.14#flattenDepth
例如
const _ = require("lodash");
const pancake = _.flatten(array)
现在,实现这一点的最佳且简单的方法是这样连接和拆分阵列。
var multipleArrays = [["$6","$Demo"], ["$12",["Multi","Deep"]], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"], ["$0"], ["$15"],["$3"], ["$75"], ["$5"], ["$100"], ["$7"], ["$3"], ["$75"], ["$5"]]
var flattened = multipleArrays.join().split(",")
此解决方案适用于多个级别,也是一个线性解决方案。
DEMO
ECMAScript 6的EDIT
由于ECMAScript 6已经标准化,您可以更改操作[].contat.apply([],arrays);对于[].contat(…数组);
var flattened = [].concat(...input);
DEMO
EDIT最高效的解决方案
解决这个问题最有效的方法是使用循环。您可以在此处比较“ops/sec”速度
var flattened=[];
for (var i=0; i<input.length; ++i) {
var current = input[i];
for (var j=0; j<current.length; ++j)
flattened.push(current[j]);
}
DEMO
希望有帮助
我写的简单的flatten util
const flatten = (arr, result = []) => {
if (!Array.isArray(arr)){
return [...result, arr];
}
arr.forEach((a) => {
result = flatten(a, result)
})
return result
}
console.log(flatten([1,[2,3], [4,[5,6,[7,8]]]])) // [ 1, 2, 3, 4, 5, 6, 7, 8 ]