我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
当前回答
我写的简单的flatten util
const flatten = (arr, result = []) => {
if (!Array.isArray(arr)){
return [...result, arr];
}
arr.forEach((a) => {
result = flatten(a, result)
})
return result
}
console.log(flatten([1,[2,3], [4,[5,6,[7,8]]]])) // [ 1, 2, 3, 4, 5, 6, 7, 8 ]
其他回答
你可以使用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>
ES6方式:
constflatten=arr=>arr.reduce((acc,next)=>acc.concat(Array.isArray(next)?flatten(next):next),[])常量a=[1,[2,[3,[4],[5]]]]console.log(flatten(a))
对于N次嵌套数组,具有ES3回退的扁平函数的ES5方式:
var flatten=(函数){if(!!Array.prototype.reduce&&!!Arrax.isArray){返回函数(数组){return array.reduce(函数(prev,next){return prev.concat(Array.isArray(next)?flatten(next):next);}, []);};}其他{返回函数(数组){var arr=[];变量i=0;var len=阵列长度;var目标;对于(;i<len;i++){目标=阵列[i];arr=arr.concat((Object.protype.toString.call(target)=='[Object Array]')?展平(目标):目标);}返回arr;};}}());var a=[1,[2,[3,[4,[5]]]];console.log(flatten(a));
var arrays=[[“$6”],[“$12”],“$25”],【“$25“],【”$18“】,【”$22“】,“$10”】,【“$15”】,“$3”】,[”$3“],[”$75“],“$5”]、[”$100“]、[“$7”]、【”$3“]、【“$75”】、【”$5“]];var merged=[].contat.apply([],数组);警报(合并);
以下代码将压平深度嵌套的数组:
/**
* [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 ]
更简单和直接的方法;可选择深压平;
const flatReduce = (arr, deep) => {
return arr.reduce((acc, cur) => {
return acc.concat(Array.isArray(cur) && deep ? flatReduce(cur, deep) : cur);
}, []);
};
console.log(flatReduce([1, 2, [3], [4, [5]]], false)); // => 1,2,3,4,[5]
console.log(flatReduce([1, 2, [3], [4, [5, [6, 7, 8]]]], true)); // => 1,2,3,4,5,6,7,8