我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
当前回答
使用那里的代码。
我会写:
myArray.enumerable().selectMany(function(x) { return x; }).array()
其他回答
这并不难,只需遍历数组并合并它们:
var result = [], input = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"]];
for (var i = 0; i < input.length; ++i) {
result = result.concat(input[i]);
}
const common = arr.reduce((a, b) => [...a, ...b], [])
我只是尝试在不使用任何内置函数的情况下解决这个问题。
var arr = [1, 3, 4, 65, [3, 5, 6, 9, [354, 5, 43, 54, 54, 6, [232, 323, 323]]]];
var result = [];
function getSingleArray(inArr) {
for (var i = 0; i < inArr.length; i++) {
if (typeof inArr[i] == "object") {
getSingleArray(inArr[i]); // Calling Recursively
} else {
result.push(inArr[i]);
}
}
}
getSingleArray(arr);
console.log(result); // [1, 3, 4, 65, 3, 5, 6, 9, 354, 5, 43, 54, 54, 6, 232, 323, 323]
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
}
只需使用扩展运算符,我们可以按以下方式展平。
var OriginalArray=[[5,1],[6],[2],[8]];var newArray=[];for(设i=0;i<OriginalArray.length;i++){newArray.push(…OriginalArray[i]);}console.log(newArray)