我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
当前回答
我认为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))
其他回答
Array.prototype.flatten = Array.prototype.flatten || function() {
return [].reduce.call(this, function(flat, toFlatten) {
return flat.concat(Array.isArray(toFlatten) ? toFlatten.flatten() : toFlatten);
},[])
};
简单并处理多个嵌套级别:
// deeply nested array
const myArray = [1, 2, [3, 4, [5, 6, [[[7,8, [[[[[9, 10]]]]]]]]]]] ;
const flatten = (arr) => {
for (let index = 0; index < arr.length; index++) {
const elem = arr[index];
if (Array.isArray(elem)) {
arr.splice(index, 1, ...elem);
index--;
}
}
};
flatten(myArray);
console.log(myArray); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
使用那里的代码。
我会写:
myArray.enumerable().selectMany(function(x) { return x; }).array()
下面是现代浏览器的另一个深层次扁平化:
function flatten(xs) {
xs = Array.prototype.concat.apply([], xs);
return xs.some(Array.isArray) ? flatten(xs) : xs;
};
有一个新的本地方法叫做flat,可以准确地执行此操作。
(截至2019年底,flat现已发布在ECMA 2019标准中,并且core-js@3(babel的库)将其包含在他们的polyfill库中)
const arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]
const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]
// Flatten 2 levels deep
const arr3 = [2, 2, 5, [5, [5, [6]], 7]];
arr3.flat(2);
// [2, 2, 5, 5, 5, [6], 7];
// Flatten all levels
const arr4 = [2, 2, 5, [5, [5, [6]], 7]];
arr4.flat(Infinity);
// [2, 2, 5, 5, 5, 6, 7];