目录
1.判断数组
// 判断数组
console.log([].constructor === Array);
console.log( Array.isArray([]));
console.log( [] instanceof Array);
console.log(Object.prototype.toString.call([]) === '[object Array]');
2.二维数组展平
const flattenOnce = (arr) => {
return [].concat(...arr)
}
const arr1 = [1, [2, 3], [4, 5, 6], [7, 8, 9, 10]];
console.log('flattenOnce',flattenOnce(arr1));
3.多维数组展平
递归
// 多维数组展平
const arr2 = [1, [2, 3], [4, 5, 6], [7, 8, 9, 10], [11, [12, 13, [14, 15]]]];
// 递归
const flatten1 = (arr) => {
return arr.reduce((acc, cur) => {
return acc.concat(Array.isArray(cur) ? flatten1(cur) : cur)
}, [])
}
console.log('flatten1',flatten1(arr2));
// 递归
const flatten2 = (arr) => {
return [].concat(...arr.map(item => Array.isArray(item) ? flatten2(item) : item))
}
console.log('flatten2',flatten2(arr2));
字符串
function flatten3(arr) {
return arr.toString().split(',').map(item => +item)
}
console.log('flatten3',flatten3(arr2));
循环
const flatten4 = (arr) => {
while(arr.some(item => Array.isArray(item))) {
arr = [].concat(...arr)
}
return arr
}
console.log('flatten4',flatten4(arr2));
栈的思想
const flatten5 = arr => {
let stack = arr.slice()
const r = []
while (stack.length) {
const item = stack.pop()
if(Array.isArray(item)){
stack = stack.concat(item) //stack.push(...item)
} else {
r.unshift(item)
}
}
return r
}
console.log('flatten5',flatten5(arr2));
生成器
function *flatten6(arr){
for (let i = 0; i < arr.length; i++) {
if(Array.isArray(arr[i])) {
yield *flatten3(arr[i])
} else{
yield arr[i]
}
}
}
console.log('flatten6', [...flatten6(arr2)]);
function *flatten7(arr) {
let stack = arr.slice()
while (stack.length) {
const item = stack.shift()
if(item.constructor === Array) {
stack = stack.concat(item) //stack.push(...item)
} else {
yield item
}
}
}
console.log('flatten7', [...flatten7(arr2)]);