es6数组去重

数组中的对象的某一元素去重 

(一)数组内的元素是基本类型的情况

const arr = [1, 2, 1, 1, null, undefined, undefined, null, "hello", "hello"]
function unique(arr) {
return Array.from(new Set(arr)) }
unique(arr);
返回:[1, 2, null, undefined, "hello"]
const arr = [1, 2, 1, 1, null, undefined, undefined, null, "hello", "hello"]
function unique(arr) {
    //定义常量 res,值为一个Map对象实例
    const res = new Map();
    
    //返回arr数组过滤后的结果,结果为一个数组
    //过滤条件是,如果res中没有某个键,就设置这个键的值为1
    return arr.filter((a) => !res.has(a) && res.set(a, 1))
}
unique(arr);
返回:[1, 2, null, undefined, "hello"]

参考链接:https://www.cnblogs.com/zhishaofei/p/9036943.html

 

(二)数组内的元素是引用的情况

function unique(arr) {
    let obj = {};
    let newArr = []; // 存放去重后的数组
 
    newArr = arr.reduce((cur, next) => {
        obj[next.props.id] ? "" : obj[next.props.id] = true && cur.push(next);
     return cur;
     },[]) //设置cur默认类型为数组,并且初始值为空的数组
     return newArr;
 }

 

(三)原生js方法

function distinct1(arr,key){
    var newobj = {},newArr = [];
    for(var i=0;i<arr.length;i++){
        var item = arr[i];
        if(!newobj[item[key]]){
            newobj[item[key]] = newArr.push(item);
        }
    }
    return newArr;
}

 

 


posted @ 2020-08-21 10:52  水晴  阅读(366)  评论(0)    收藏  举报