数组去重
//新时代新方法
[...new Set(arr)]
//显然上述是取巧的方法,使用map
const map = new Map()
arr.forEach(x=>{
//这里的1是随意值
map.set(x,1)
})
//之后吧map的key全部取出来就可以了
const newArr = Array.from(map.keys())
数组扁平化
解题思路
遍历数组,拿出所有值重组一个数组
[[1,2],[3,[4,5]] -> [1,2,3,4]
//第一步怎么拿出所有的值
let arr = [[1,2],[3,4]]
let stack = []
let item = arr.pop()
//退出条件,arr.pop()为undefined
while(item !== undefined){
//如果item是array我们就要继续分解
if(Array.isArray(item)){
let midItem = item.pop()
item.length == 0 ? '' : arr.push(item)
item = midItem
} else {
//不是array我们就push进结果栈
stack.push(item)
item = arr.pop()
}
}
//将结果栈反转,获得打平后的数组
const result = stack.reverse()