使用each和reduce函数创建flatten函数:
function each(collection, iterator) {
if (Array.isArray(collection)){
for (var i=0;i<collection.length;i++){
iterator(collection[i],i,collection)
}
}else {
for (var key in collection){
iterator(collection[key],key,collection)
}
}
};
function reduce(collection, iterator, accumulator) {
var initalizing = arguments.length === 2;
each(collection,function(value){
accumulator = iterator(accumulator,value);
});
return accumulator;
};
我尝试使用每个迭代嵌套数组,如果toFlatten
是数组,它会将value
推送到array
。如果它不是数组,它会将累积的flat
数字推送到数组...为什么它不起作用?
function flatten(array){
return reduce(array,function(flat,toFlatten){
return each(toFlatten,function(value){
if(Array.isArray(toFlatten)){
return array.push(value);
}
});
return array.push(flat)
},[]);
};
flatten([[1,2,3],2,3,[3,4,5],5,6]); //nothing returned
flatten([[1,2,3],2,3,[3,[4,7],5],5,6]);
更新答案:
function flatten(array) {
return reduce(array,function(flat,toFlatten){
if(Array.isArray(toFlatten)){
each(toFlatten,function(value){
flat.push(value);
});
}else{
flat.push(toFlatten)
}
return flat;
},[]);
}
答案 0 :(得分:2)
以下是您的示例略有变化(请参阅评论)并使用Array.prototype.map()和Array.prototype.forEach():
function flatten(array) {
return array.reduce(function (flat, toFlatten) {
if (Array.isArray(toFlatten)) {
// if it is an array, iterate it and push each value to flatted result
toFlatten.forEach(function (value) {
if (Array.isArray(toFlatten)) {
flat.push(value);
}
});
} else {
// if it is not an array, just push the value to result
flat.push(toFlatten);
}
return flat; // return new flatted result
}, []);
};
flatten([[1, 2, 3], 2, 3, [ 3, 4, 5 ], 5, 6]);
// Array [ 1, 2, 3, 2, 3, 3, 4, 5, 5, 6 ]
但是你可以通过调用Array.prototype.concat()上的apply方法来缩短它:
Array.prototype.concat.apply([], [[1, 2, 3], 2, 3, [ 3, 4, 5 ], 5, 6]);
您也可以将它用于深层嵌套数组:
var array = [[1, 2, 3], 2, 3, [3, [4, 7], 5], 5, 6];
while(array.some(Array.isArray)) {
array = Array.prototype.concat.apply([], array);
}
console.log(array);