手写系列之数组去重 - 图1


本文章列举了多个数组去重的方式。接下来会针对代码一一讲解

方法1

  1. [...new Set(arr)]
  • 利用Set的元素不能重复的特性进行去重

    方法2

    1. function fn1() {
    2. const result = []
    3. arr.forEach((item) => {
    4. if (!result.includes(item)) result.push(item)
    5. })
    6. return result
    7. }
  • 循环遍历判断数组中是否有同样的值存在,没有添加,反之跳过

    方法3

    1. function fn2() {
    2. const double = []
    3. const other = []
    4. arr.forEach((item) => {
    5. if (arr.indexOf(item) === arr.lastIndexOf(item)) {
    6. other.push(item)
    7. } else if (!double.includes(item)) {
    8. double.push(item)
    9. }
    10. })
    11. return double.concat(other)
    12. }
  • 利用indexOf 以及lastIndexOf进行判断,如果不相等说明有重复值

    方法4

    1. function fn3() {
    2. return arr.filter((item, index) => {
    3. return arr.indexOf(item) === index
    4. })
    5. }
  • 利用filter以及indexOf进行筛选