js数组扁平化
2019-07-29 本文已影响0人
没了提心吊胆的稗子
1、 利用apply和concat转换
function reduceDimension(arr) {
return Array.prototype.concat.apply([], arr);
}
2、reduce
let flat = [[1,2,3],[4,5,6],[7,8,9]].reduce((prev, next) => {
return prev.concat(next)
});
3、多维数组递归降维
let arr = [[12], 4, [333, [4444, 5555]], [9, [111, 222]]];
function arrayConcat(ary, point) {
return [].concat.apply(point || [], ary);
}
function reduceDimesion(ary) {
var arrays = arrayConcat(ary);
let newAry = [];
for (var i = 0, len = arrays.length; i < len; i++) {
if({}.toString.call(arrays[i]) === '[object Array]'){
newAry = arrayConcat(arrays[i], newAry);
} else {
newAry.push(arrays[i]);
}
}
return newAry;
}
// 扩展 : n表示降多少维
function reduceDimesion(ary, n) {
var arrays = arrayConcat(ary);
let newAry = [];
for (var i = 0, len = arrays.length; i < len; i++) {
if({}.toString.call(arrays[i]) === '[object Array]' && n-- > 1){
newAry = arrayConcat(arrays[i], newAry);
} else {
newAry.push(arrays[i]);
}
}
return newAry;
}