美文网首页
JavaScript数组去重

JavaScript数组去重

作者: 段煜华 | 来源:发表于2020-01-13 19:42 被阅读0次

    JavaScript中数组的常用操作之数组去重

    方法一

    var color = ['red','blue','green','yellow','black','white','green','blue','pink','gold','cyan'];
    //第一种方法
    var uniqueColor = Array.from(new Set(color));
    console.log(uniqueColor)
    //第二种方法
    var uniqueColor = [...new Set(color)]
    console.log(uniqueColor)
    

    方法二

    const arr=[{id:1,value:'bob'},{id:1,value:'bob'},{id:1,value:'bob'},{id:1,value:'lucy'},{id:1,value:'lucy'},{id:2,name:'lucy'},{id:2,name:'张三'}]
    const newArr = arr.reduce((result, item) => {
            if (!result.find(x => x.value === item.value)) {
              result.push(item);
            }
            return result;
    }, []);
    

    相关文章

      网友评论

          本文标题:JavaScript数组去重

          本文链接:https://www.haomeiwen.com/subject/squnactx.html