我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
当前回答
只需使用扩展运算符,我们可以按以下方式展平。
var OriginalArray=[[5,1],[6],[2],[8]];var newArray=[];for(设i=0;i<OriginalArray.length;i++){newArray.push(…OriginalArray[i]);}console.log(newArray)
其他回答
const common = arr.reduce((a, b) => [...a, ...b], [])
我认为array.flat(Infinity)是一个完美的解决方案。但平面功能是一个相对较新的功能,可能不会在旧版本的浏览器中运行。我们可以使用递归函数来解决这个问题。
常量arr=[“A”,[“B”,[[“B11”,“B12”,[”B131“,“B132”]],“B2”]],”C“,[”D“,”E“,”F“,[“G”,“H”,“I”]]]常量flatArray=(arr)=>{常量res=[]for(arr的常量项){if(Array.isArray(项)){const subRes=flatArray(项)资源推送(…subRes)}其他{res.push(项目)}}返回res}console.log(flatArray(arr))
我使用这个方法来展开混合数组:(这对我来说似乎最简单)。用较长的版本来解释步骤。
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)
let arr = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"], ["$0"], ["$15"],["$3"], ["$75"], ["$5"], ["$100"], ["$7"], ["$3"], ["$75"], ["$5"]];
arr = arr.reduce((a, b) => a.concat(b)); // flattened
我最初想使用.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安慰