三种数组去重方法

技术博客 (43) 2024-01-01 09:01:01

使用Set

var array1 = [1,"1",2,1,3,4,5,2,"1","2"];
function unique1(arr){
  return [...new Set(arr)]
}
var newArray1 = unique1(array1);
console.log(newArray1); // [ 1, "1", 2, 3, 4, 5, "2" ]

使用filter

var array2 = ["10",20,10,30,40,50,20,"10","20"];
function unique2(arr){
  var obj = {};
  return arr.filter((item) => {
    if(!obj[item]){
      obj[item] = true;
      return true;
    }
  })
}
var newArray2 = unique2(array2);
console.log(newArray2); // [ "10", 20, 30, 40, 50 ]

该方法存在一个弊端,当数组为[1,“1”,2]时,结果为[1,2]。当数组为[“1”,1,2]时,结果为[“1”,2]。

使用IndexOf

var array3 = [100,"100",200,100,300,400,500,200,"100","200"];
function unique3(arr){
  var result = [];
  arr.forEach((item) => {
    if(result.indexOf(item) === -1){
      result.push(item)
    }
  })
  return result;
}
var newArray3 = unique3(array3);
console.log(newArray3); // [ 100, "100", 200, 300, 400, 500, "200" ]
THE END

发表回复