JS数组去重

去除数组中的重复元素

思路主要是遍历,然后去重

/**
*数组去重
*@param arr{Array}原始数组
*@return {Array}去重后的数组
*/
function distinctArray(arr){
     var rel=[];
     for(var i=0;i<arr.length;i++){
          if(rel.indexOf(arr[i]) === -1){
              rel.push(arr[i]); 
          }
     }
     return rel;
}

上述代码可进行简化

Array.prototype.unique = function() {

//如果数组中的某一项的在数组中第一次出现的位置和当前index不相等,说明这一项是重复的

    return this.filter((item, index) => this.indexOf(item) === index) 
}

  

也可以使用ES6中的Set,Set 对象允许你存储任何类型的唯一值,无论是原始值或者是对象引用 

Array.prototype.uniqe=function(){
  return Array.from(new Set(this));  
}

 关于Set的用法 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Set

参考地址:https://segmentfault.com/a/1190000010798151

原文地址:https://www.cnblogs.com/jingmi-coding/p/9295727.html