跳到主要内容

一、 数组去重

  • 两层 for 循环对比
  • 使用 Set 去重
  • 使用 indexOf 存在校验,不存在则 push 进新数组
  • 使用 sort 排序后比较(但是会破坏原数组的元素顺序)
  • 使用 includes (es7 才支持)
  • 使用 hasOwnProperty
  • 使用 filter
  • 使用递归
  • 使用 Map (es6 后才支持)

二、 扁平化处理

  • 使用 Array.prototype.flat() (ES10 后才支持)
  • 使用 reduce() + concat() 经典递归方法
  • 使用 reduce() + push() + 递归 (性能更优)
  • 使用 toString() + split() 进行简单粗暴的扁平化
  • 使用栈(Stack)实现迭代扁平化(防止递归调用栈溢出)
/**
* 使用 flat
*
* 返回:`[1, 2, 3, 4, 5, 6]`
*
*/
console.log([1, [2, [3, [4, [5, [6]]]]]].flat(Infinity));

/**
* 使用 flatMap 进行扁平化 (只能扁平化一层)
*
* 返回:`[4, 2, [3, [4, [5, [6]]]]]`
*/
console.log(
[1, [2, [3, [4, [5, [6]]]]]].flatMap(item =>
!Array.isArray(item) ? (++item) ** 2 : item,
),
);

/** 使用 `reduce()` 和 `concat()` */
function flattenOfReduceWithConcat(arr) {
return arr.reduce(
(acc, val) =>
Array.isArray(val)
? acc.concat(flattenOfReduceWithConcat(val))
: acc.concat(val),
[],
);
}

/** 使用 `reduce()` + `push()` + 递归 */
function flattenOfReduceWithPush(arr) {
return arr.reduce((acc, item) => {
if (Array.isArray(item)) {
acc.push(...flattenOfReduceWithPush(item));
} else acc.push(item);
return acc;
}, []);
}

/** 使用栈进行迭代扁平化 */
function flattenOfStack(arr) {
const stack = [...arr];

const result = [];

while (stack.length) {
const next = stack.pop();
if (Array.isArray(next)) {
stack.push(...next);
} else {
result.unshift(next);
}
}

return result;
}