外观
假定有一个多维数组:
const multidimensionalArray = [
[1, 2, 3],
[1, 3],
[4, 5, 6],
{ a: 3 },
null,
]我们想获取与之对应的扁平化、去重了的的一维数组:
该如何实现呢?
数组去重其实就是new Set处理一下即可,这种去重方法写起来最简便,例如:
[...new Set([1, 2, 3, 2, 1, 3])] // [1, 2, 3]数组扁平化其实就是先定义一个空数组tempArr,然后遍历原数组的元素,如果被遍历元素不是数组类型就直接添加到tempArr中,如果是数组类型则递归处理这个数组元素重复刚才的操作。在这个遍历过程中,其实我们可以直接一步到位做好是否为重复元素的判断,这样就不用另外做数组的去重处理了。
const flattenArray = (arr) => {
const tempArr = []
const tempMap = new Map()
const handleItem = (item) => {
if (Array.isArray(item)) {
item.forEach(handleItem)
return
}
// 判断重复性,若重复则不添加
if (tempMap.has(item)) {
return
}
tempArr.push(item)
tempMap.set(item, true)
}
handleItem(arr)
return tempArr
}