我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
当前回答
如果只有一个字符串元素的数组:
[["$6"], ["$12"], ["$25"], ["$25"]].join(',').split(',');
将完成这项工作。与您的代码示例具体匹配的Bt。
其他回答
const flatten = array => array.reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []);
根据请求,分解一行基本上就是这样。
function flatten(array) {
// reduce traverses the array and we return the result
return array.reduce(function(acc, b) {
// if is an array we use recursion to perform the same operations over the array we found
// else we just concat the element to the accumulator
return acc.concat( Array.isArray(b) ? flatten(b) : b);
}, []); // we initialize the accumulator on an empty array to collect all the elements
}
ES2019年
ES2019引入了Array.protocol.flat()方法,您可以使用它来展平阵列。它与大多数环境兼容,尽管它仅在Node.js版本11开始提供,而在Internet Explorer中根本不提供。
常量数组=[["$6"],["$12"],["$25"],["$25"],["$18"],["$22"],["$10"]];const merge3=arrays.flat(1)//指定嵌套数组结构应展平的深度级别。默认值为1。console.log(合并3);
较旧的浏览器
对于较旧的浏览器,可以使用Array.prototype.cocat合并数组:
var数组=[["$6"],["$12"],["$25"],["$25"],["$18"],["$22"],["$10"]];var merged=[].contat.apply([],数组);console.log(合并);
使用concat的apply方法将只将第二个参数作为数组,因此最后一行与此相同:
var merged = [].concat(["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]);
只需使用扩展运算符,我们可以按以下方式展平。
var OriginalArray=[[5,1],[6],[2],[8]];var newArray=[];for(设i=0;i<OriginalArray.length;i++){newArray.push(…OriginalArray[i]);}console.log(newArray)
我有一个简单的解决方案,不用在特殊的js函数中使用。(如减少等)
const input = [[0, 1], [2, 3], [4, 5]]
let flattened=[];
for (let i=0; i<input.length; ++i) {
let current = input[i];
for (let j=0; j<current.length; ++j)
flattened.push(current[j]);
}
要展平单个元素数组的数组,不需要导入库,简单的循环是最简单和最有效的解决方案:
for (var i = 0; i < a.length; i++) {
a[i] = a[i][0];
}
对反对选民:请阅读问题,不要因为它不适合你的不同问题而反对投票。对于所问的问题,此解决方案是最快和最简单的。