zoukankan      html  css  js  c++  java
  • 数组去重

    数组对象去重

    需求:

    多组数组元素组合拼接,最终导致数组中有一些重复出现的元素。现将数组中重复的元素剔除掉,最终得到一组没有重复数据的新数组对象。

    解决方法:

    采用 reduce() 处理数组元素,达到最终目的;

    • reduce()方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值;
    • reduce()可以作为一个高阶函数,用于函数的 compose;
    • 注意reduce()对于空数组是不会执行回调函数的。

    语法:

    array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

    • 参数:
    total 必需。初始值,或者计算结束后的返回值。
    currentValue 必需。当前元素。
    currentIndex 可选。当前元素索引
    arr 可选。当前元素所属的数组对象
    initialValue 可选。传递给函数的初始值

    实现代码:(过滤数组对象中的重复元素)

    const filterArray = (array) => {
    	let tmp = {};
    	let tmpArray = array.reduce((total, item) => {
    		tmp[item.id] ? '' : (tmp[item.id] = total.push(item));
    		return total
    	}, []);
    	return tmpArray;
    }
    

    实例使用:

    // 使用
    let testArray = [{
    	id: 1,
    	name: 'zhangsan'
    }, {
    	id,
    	2,
    	name: 'lisi'
    }, {
    	id: 1,
    	'zhangsan'
    }, {
    	id: 4,
    	name: 'wangwu'
    }];
    // 过滤后数据
    let newArray = filterArray(testArray);
    
    newArray = [{
    	id: 1,
    	name: 'zhangsan'
    }, {
    	id,
    	2,
    	name: 'lisi'
    }, {
    	id: 4,
    	name: 'wangwu'
    }];
    
  • 相关阅读:
    ThinkPHP Ajax 使用详解及实例
    thinkphp中常用的系统常量和系统变量
    JavaScript使用thinkPHP模板标签
    正则表达式替换连续空格
    javascript关联数组
    javascript关联数组的用法
    javascript之数组操作
    CentOS7_开放指定端口
    centos7磁盘基本信息
    SpringBoot thymeleaf——修改后如何实时生效
  • 原文地址:https://www.cnblogs.com/zxk5211/p/13706879.html
Copyright © 2011-2022 走看看