我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
当前回答
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));
其他回答
[1,[2,3],[4,[5,6]]].reduce(function(p, c) {
return p.concat(c instanceof Array ?
c.reduce(arguments.callee, []) :
[c]);
}, []);
const flatten = array => array.reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []);
根据请求,分解一行基本上就是这样。
function flatten(array) {
// reduce traverses the array and we return the result
return array.reduce(function(acc, b) {
// if is an array we use recursion to perform the same operations over the array we found
// else we just concat the element to the accumulator
return acc.concat( Array.isArray(b) ? flatten(b) : b);
}, []); // we initialize the accumulator on an empty array to collect all the elements
}
function flatten(input) {
let result = [];
function extractArrayElements(input) {
for(let i = 0; i < input.length; i++){
if(Array.isArray(input[i])){
extractArrayElements(input[i]);
}else{
result.push(input[i]);
}
}
}
extractArrayElements(input);
return result;
}
// let input = [1,2,3,[4,5,[44,7,8,9]]];
// console.log(flatten(input));
// output [1,2,3,4,5,6,7,8,9]
我只是尝试在不使用任何内置函数的情况下解决这个问题。
var arr = [1, 3, 4, 65, [3, 5, 6, 9, [354, 5, 43, 54, 54, 6, [232, 323, 323]]]];
var result = [];
function getSingleArray(inArr) {
for (var i = 0; i < inArr.length; i++) {
if (typeof inArr[i] == "object") {
getSingleArray(inArr[i]); // Calling Recursively
} else {
result.push(inArr[i]);
}
}
}
getSingleArray(arr);
console.log(result); // [1, 3, 4, 65, 3, 5, 6, 9, 354, 5, 43, 54, 54, 6, 232, 323, 323]
有一种比使用上面的答案中列出的merge.contat.apply()方法快得多的方法来实现这一点,我的意思是速度快几个数量级。这假设您的环境可以访问ES5 Array方法。
var array2d = [
["foo", "bar"],
["baz", "biz"]
];
merged = array2d.reduce(function(prev, next) {
return prev.concat(next);
});
这里是jsperf链接:http://jsperf.com/2-dimensional-array-merge