我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
当前回答
如果您需要支持IE8,因此无法使用reduce或isArray等方法,这里有一个可能的解决方案。这是一种冗长的方法,可以帮助您理解递归算法。
function flattenArray(a){
var aFinal = [];
(function recursiveArray(a){
var i,
iCount = a.length;
if (Object.prototype.toString.call(a) === '[object Array]') {
for (i = 0; i < iCount; i += 1){
recursiveArray(a[i]);
}
} else {
aFinal.push(a);
}
})(a);
return aFinal;
}
var aMyArray = [6,3,4,[12,14,15,[23,24,25,[34,35],27,28],56],3,4];
var result = flattenArray(aMyArray);
console.log(result);
其他回答
另一种方法是使用jQuery$.map()函数。从jQuery文档:
该函数可以返回一个值数组,该数组将被展平为完整数组。
var source = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]];
var target = $.map(source, function(value) { return value; }); // ["$6", "$12", "$25", "$25", "$18", "$22", "$10"]
以下代码将压平深度嵌套的数组:
/**
* [Function to flatten deeply nested array]
* @param {[type]} arr [The array to be flattened]
* @param {[type]} flattenedArr [The flattened array]
* @return {[type]} [The flattened array]
*/
function flattenDeepArray(arr, flattenedArr) {
let length = arr.length;
for(let i = 0; i < length; i++) {
if(Array.isArray(arr[i])) {
flattenDeepArray(arr[i], flattenedArr);
} else {
flattenedArr.push(arr[i]);
}
}
return flattenedArr;
}
let arr = [1, 2, [3, 4, 5], [6, 7]];
console.log(arr, '=>', flattenDeepArray(arr, [])); // [ 1, 2, [ 3, 4, 5 ], [ 6, 7 ] ] '=>' [ 1, 2, 3, 4, 5, 6, 7 ]
arr = [1, 2, [3, 4], [5, 6, [7, 8, [9, 10]]]];
console.log(arr, '=>', flattenDeepArray(arr, [])); // [ 1, 2, [ 3, 4 ], [ 5, 6, [ 7, 8, [Object] ] ] ] '=>' [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
制作平面阵列的方法
使用Es6 flat()使用Es6 reduce()使用递归使用字符串操作
[1,[2,[3,[4,[5,[6,7],8],9],10]]] - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
//使用Es6 flat()设arr=[1,[2,[3,[4,[5,[6,7],8],9],10]]]console.log(arr.flat(无限))//使用Es6 reduce()let flatIt=(array)=>array.reduce((x,y)=>x.concat(Array.isArray(y)?flatIt(y):y),[])console.log(flatIt(arr))//使用递归函数myFlat(数组){let flat=[].contat(…数组);返回flat.some(Array.isArray)?myFlat(平面):平面;}console.log(myFlat(arr));//使用字符串操作let strArr=arr.toString().split(',');for(设i=0;i<strArr.length;i++)strArr[i]=parseInt(strArr[i]);console.log(strArr)
我认为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))
这是一个基于artif3x答案的Typescript版本,为Scala粉丝提供了flatMap的额外实现。
function flatten<T>(items: T[][]): T[] {
return items.reduce((prev, next) => prev.concat(next), []);
}
function flatMap<T, U>(items: T[], f: (t: T) => U[]): U[] {
return items.reduce((prev, next) => prev.concat(f(next)), new Array<U>());
}