js二维数组展平
let arr = [1, [2], [3, 4], [4, [5, 6]], 7];
function flattenMd(arr) {
let res = [];
function flatten(arr) {
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
flatten(arr[i]);
} else {
res.push(arr[[i]]);
}
}
}
flatten(arr);
return res;
}
console.log(flattenMd(arr));
function flattenMd(arr) {
var result = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] instanceof Array) {
result = result.concat(flattenMd(arr[i]));
} else {
result.push(arr[i]);
}
}
return result;
}
console.log(flattenMd(arr));
function flatten(arr) {
return arr.reduce(function (plane, toBeFlatten) {
return plane.concat(
Array.isArray(toBeFlatten) ? flatten(toBeFlatten) : toBeFlatten
);
}, []);
}
console.log(flatten(arr));
flatten1 = function (arr) {
return arr.reduce(
(plane, toBeFlatten) =>
plane.concat(
Array.isArray(toBeFlatten) ? flatten(toBeFlatten) : toBeFlatten
),
[]
);
};
console.log(flatten1(arr));
flatten2 = (arr) =>
arr.reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []);
console.log(flatten2(arr));
function deepFlatten(arr) {
flatten = (arr) => [].concat(...arr);
return flatten(arr.map((x) => (Array.isArray(x) ? deepFlatten(x) : x)));
}
console.log(deepFlatten(arr));
function flattenMdd(arr) {
return arr.join().split(",");
}
console.log(flattenMdd(arr));
function flatArr(arr,flatFlag){
return arr.flat(flatFlag);
}
console.log(flatArr(arr,1)
console.log(flatArr(arr,2)