我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
当前回答
要在一行中展平二维阵列,请执行以下操作:
[[1, 2], [3, 4, 5]].reduce(Function.prototype.apply.bind(Array.prototype.concat))
// => [ 1, 2, 3, 4, 5 ]
其他回答
如果只有一个字符串元素的数组:
[["$6"], ["$12"], ["$25"], ["$25"]].join(',').split(',');
将完成这项工作。与您的代码示例具体匹配的Bt。
以下代码将压平深度嵌套的数组:
/**
* [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 ]
Haskell式方法
函数flatArray([x,…xs]){返回x?[…Array.isArray(x)?flatArray(x):[x]。。。flatArray(xs)]:[];}var na=[[1,2],[3,[4,5]],[6,7,[[[8],9],10];fa=平面阵列(na);console.log(fa);
如果您的数组仅由整数或字符串组成,则可以使用这种肮脏的方法:
var arr = [345,2,[34],2,[524,[5456]],[5456]];
var flat = arr.toString().split(',');
Works,在FF、IE和Chrome中还没有测试其他浏览器。
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));