开发者社区 问答 正文

去除数组重复成员的方法

去除数组重复成员的方法

展开
收起
茶什i 2019-11-22 14:25:55 947 分享 版权
1 条回答
写回答
取消 提交回答
  • 方法 1 扩展运算符和 Set 结构相结合,就可以去除数组的重复成员

    // 去除数组的重复成员
    [...new Set([1, 2, 2, 3, 4, 5, 5])];
    // [1, 2, 3, 4, 5]
    

    方法 2

    function dedupe(array) {
      return Array.from(new Set(array));
    }
    dedupe([1, 1, 2, 3]); // [1, 2, 3]
    
    

    方法 3(ES5)

    function unique(arry) {
      const temp = [];
      arry.forEach(e => {
        if (temp.indexOf(e) == -1) {
          temp.push(e);
        }
      });
    
      return temp;
    }
    
    2019-11-22 14:27:04
    赞同 展开评论
问答地址: