我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
当前回答
const common = arr.reduce((a, b) => [...a, ...b], [])
其他回答
我已经使用递归和闭包完成了
function flatten(arr) {
var temp = [];
function recursiveFlatten(arr) {
for(var i = 0; i < arr.length; i++) {
if(Array.isArray(arr[i])) {
recursiveFlatten(arr[i]);
} else {
temp.push(arr[i]);
}
}
}
recursiveFlatten(arr);
return temp;
}
你可以使用Ramda JS flatten
var arr=[[1,2],[3],[4,5]];var flattedArray=R.flatten(arr);console.log(flattedArray)<script src=“https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js“></script>
Array.prototype.flatten = Array.prototype.flatten || function() {
return [].reduce.call(this, function(flat, toFlatten) {
return flat.concat(Array.isArray(toFlatten) ? toFlatten.flatten() : toFlatten);
},[])
};
深度扁平化和面向对象怎么样?
[23, [34, 454], 12, 34].flatten();
// --> [23,34, 454, 12, 34]
[23, [34, 454,[66,55]], 12, 34].flatten();
// --> [23, 34, 454, [66,55], 12, 34]
深压平:
[23, [34, 454,[66,55]], 12, 34].flatten(true);
// --> [23, 34, 454, 66, 55, 12, 34]
DEMO
CDN
如果所有数组元素都是Integer、Float,。。。或/和字符串,所以只需执行以下操作:
var myarr=[1,[7,[9.2]],[3],90];
eval('myarr=['+myarr.toString()+']');
print(myarr);
// [1, 7, 9.2, 3, 90]
DEMO
我使用这个方法来展开混合数组:(这对我来说似乎最简单)。用较长的版本来解释步骤。
function flattenArray(deepArray) {
// check if Array
if(!Array.isArray(deepArray)) throw new Error('Given data is not an Array')
const flatArray = deepArray.flat() // flatten array
const filteredArray = flatArray.filter(item => !!item) // filter by Boolean
const uniqueArray = new Set(filteredArray) // filter by unique values
return [...uniqueArray] // convert Set into Array
}
//较短版本:
const flattenArray = (deepArray) => [...new Set(deepArray.flat().filter(item=>!!item))]
flattenArray([4,'a', 'b', [3, 2, undefined, 1], [1, 4, null, 5]])) // 4,'a','b',3,2,1,5
Codesandbox链接
现代方法
使用[].flat(Infinity)方法
const nestedArray = [1,[2,[3],[4,[5,[6,[7]]]]]]
const flatArray = nestedArray.flat(Infinity)
console.log(flatArray)