zoukankan      html  css  js  c++  java
  • JavaScript实战笔记(二) 数组去重

    这篇文章介绍数组去重的几种方法

    1、利用 Set 去重

    利用集合元素唯一的性质,去除重复的元素,但是不能去除相同的对象(id 不同)

    function unique(array) {
        return [...new Set(array)] 
    }
    

    2、利用 Map 去重

    利用映射键值唯一的性质,去除重复的元素,但是不能去除相同的对象(id 不同)

    function unique(array) {
        let result  = new Array()
        let mapping = new Map()
        for (let item of array) {
            if(!mapping.has(item)) {
                mapping.set(item)
                result.push(item)
            }
        }
        return result
    }
    

    3、双层循环

    外层循环遍历数组的每一个元素,内层循环判断当前元素是否在结果数组中

    function unique(arr) {
        let res = []
        for (let i = 0, arrlen = arr.length; i < arrlen; i++) {
            let isUnique = true
            for (let j = 0, reslen = res.length; j < reslen; j++) {
                if (arr[i] === res[j]) {
                    isUnique = false
                    break
                }
            }
            if (isUnique) res.push(arr[i])
        }
        return res
    }
    

    注意,这种方法不能去除相同的对象和重复的 NaN

    4、单层循环 + 语言特性

    使用循环遍历数组的每一个元素,使用 indexOf 方法判断当前元素是否在结果数组中

    function unique(arr) {
        let res = []
        for (let ind = 0, len = arr.length; ind < len; ind++) {
            let val = arr[ind]
            if (res.indexOf(val) === -1) res.push(val)
        }
        return res
    }
    

    注意,这种方法不能去除相同的对象和重复的 NaN

    【 阅读更多 JavaScript 系列文章,请看 JavaScript学习笔记

  • 相关阅读:
    zookeeper C API
    《accelerated c++》第九章---设计类
    redis memcache 比较
    redis 学习记录
    php memcache 使用学习
    php新手需要注意的高效率编程
    linux常用命令
    curl和file_get_contents 区别以及各自的优劣
    php序列化问题
    socket编程 123
  • 原文地址:https://www.cnblogs.com/wsmrzx/p/12305201.html
Copyright © 2011-2022 走看看