zoukankan      html  css  js  c++  java
  • 普通数组/数组对象去重的几种方法

    一、数组去重

      (1)ES5方法! 利用 filter 和 indexOF方法

    复制代码
    
    
    let arr = [1, 1, 2, 3, undefined, null, null, 23, 'g', 'g']
    function uniq (array){
     return [].filter.call(array, function (item, index) { 
        return array.indexOf(item) == index 
        })
    }

    console.log(uniq(arr)) // [1, 2, 3, undefined, null, 23, "g"]
    复制代码

      

      (2)ES6方法! 利用 new Set()方法配合ES6 展开运算符: Set 对象允许你存储任何类型的唯一值,无论是原始值或者是对象引用

    let arr = [1, 1, 2, 3, undefined, null, null, 23, 'g', 'g']
    console.log([...new Set(arr)]) // [1, 2, 3, undefined, null, 23, "g"]

      (3)ES6方法! 利用 reduce

       

    复制代码
    (1)对普通数组去重
    let arr = arr = [1, 2 , 2, ,3, 2 ,4 ,1, 1, 1, 2]
    
    let newArr = arr.reduce(function (item, next) {
        obj[next] ? '' : obj[next] = true && item.push(next)
        return item
    }, [])
    console.log(newArr) // [1, 2, 3, 4]
    
    (2)数组对象去重
    
    let arr2 = [
        {id: 1},
        {id: 1},
        {id: 1},
        {id: 2},
        {id: 4},
    ]
    let newArr2 = arr.reduce(function (item, next) {
        console.log(item)
        obj[next.id] ? '' : obj[next.id] = true && item.push(next)
        return item
    }, [])
    console.log(newArr2)
    复制代码

    二、数组某项第一个查找

      find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined

    const array1 = [5, 12, 8, 130, 44];
    
    const found = array1.find(item => item > 10);
    
    console.log(found); // 12

    三、数组遍历,可中断和不可中断 循环

      除了简单的 for , do...while 循环外,还有 forEach,map

       for 可以用 break 跳出循环遍历外,forEach,map 不能跳出遍历,

    复制代码
    let arr = [1, 1, 2, 3, undefined, null, null, 23, "g", "g"]
    
    for (let i = 0, len = arr.length; i < arr.len; i++) {
        console.log(i) // 0, 1, 2, 3
        if (i === 3) {
            break // 注意仅可用 break退出循环
        }
    }
  • 相关阅读:
    编写一个程序的步骤
    vue实现瀑布流
    Vue 解决动态生成列表点击事件无效的问题
    筛选分类列表展示
    php实现类似慕课网,php中文网的分类功能
    在一个页面修改数据,并且ajax刷新数据列表的数据实现。
    记账小程序系统简单规划
    茶叶项目---产品的规格添加
    茶叶商城开发
    后端图片上传
  • 原文地址:https://www.cnblogs.com/lgnblog/p/12518320.html
Copyright © 2011-2022 走看看