数组去重,取重的方法

这里记录自己常用的两种方法

第一种是使用的javascript的 indexOf 方法

第二种是使用对象中的属性查找的方法。

方法一:

// 去重取重
var arr = [1,2,3,4,12,3,4,5,2,1];
var res = [];
var res2 = [];
for(var i=0;i<arr.length;i++){
  console.log(arr[i])
  if (res.indexOf(arr[i]) == -1){
    res.push(arr[i]);
  } else {
    res2.push(arr[i]);
  }
}
console.log(res) //[1, 2, 3, 4, 12, 5]
console.log(res2) //[3, 4, 2, 1]

方法二:
// 去重
var arr2 = [1,2,4,5,3,2,1,3,4,2,4,5,4,234];
var o = {};
var resultArr = [];
for(var i=0;i<arr2.length;i++){
  if(!o[arr2[i]]){
    resultArr.push(arr2[i]);
    o[arr2[i]] = 2
  }
}
console.log(resultArr) //[1, 2, 4, 5, 3, 234]

封装成javascript原生数组方法如下:

Array.prototype.unique = function(){
 var res = [];
 var o = {};
 for(var i = 0; i < this.length; i++){
  if(!o[this[i]]){
   res.push(this[i]);
   o[this[i]] = 1;
  }
 }
 return res;
}

原文地址:https://www.cnblogs.com/yu-709213564/p/7886291.html