• Javascript数组去重


    1、ES6 Set

    const arr = [1, 2, 1, 2, 3 ,4, 5]
    
    const unique = (arr) => {
      return Array.from(new Set(arr))  // return [...new Set(arr)]
    }
    
    unique(arr)
    
    

    2、利用indexOf、includes

    const arr = [1, 2, 1, 2, 3 ,4, 5]
    
    const unique = (arr) => {
      let result = []
      for (let i of arr) {
      	if (result.indexOf(i) === -1) {  // if (!result.includes(i))
        	result.push(i)
        }
      }
      return result
    }
    
    unique(arr)
    
    

    3、for 循环嵌套

    const arr = [1, 2, 1, 2, 3 ,4, 5]
    
    const unique = (arr) => {
      for (let i = 0, len = arr.length; i < len; i++) {
      	for(let j = i + 1, len = arr.length; j < len; j++) {
          if(arr[i] === arr[j]) {
          	arr.splice(i, 1)
            j--
          }
        }
      }
      return arr
    }
    
    unique(arr)
    复制代码
    

    4、filter + indexOf

    const arr = [1, 2, 1, 2, 3 ,4, 5]
    
    const unique = (arr) => {
      return arr.filter((item, index) => arr.indexOf(item) === index)
    }
    
    unique(arr)
    

    5、reduce + includes

    const arr = [1, 2, 1, 2, 3 ,4, 5]
    
    const unique = (arr) => {
      return arr.reduce((prev, curr) => prev.includes(curr) ? prev : [...prev, curr], [])
    }
    
    unique(arr)
    

    6、sort

    const arr = [1, 2, 1, 2, 3 ,4, 5]
    
    const unique = (arr) => {
      arr = arr.sort()
      let result = [arr[0]]
      for (let i = 1, len = arr.length; i < len; i++) {
      	if (arr[i] !== arr[i-1]) {
          result.push(arr[i])
        }
      }
      return result
    }
    
    unique(arr)
    
  • 相关阅读:
    15 react ajax 请求 github 用户信息
    14 react fetch
    13 React axios
    12 脚手架编写React项目(评论管理)---
    gitlab init project
    为什么是2MSL而不是MSL?
    mac python install zlib not available
    Laravel 传递数据到视图
    sleep(0)作用
    ping错误详解
  • 原文地址:https://www.cnblogs.com/pp-yang/p/14923432.html
Copyright © 2020-2023  润新知