JS 高效快速的数组去重

时间:2021-05-10 00:16:14

Array.prototype.uniquer = function() {
  var hash = {},
  newarr = [],
  type;
  for (var i = 0; i < this.length; i++) {
    type = typeof(this[i])//用type来存储一下数据类型
    if (!hash[this[i]]) {
      newarr.push(this[i]);
      hash[i] = type;
    } else if (hash[this[i]].indexOf(type) < 0) {
      newarr.push(this[i]);
      hash[i] = type;
    }
  }
  return newarr;
} var a = [1, 2, '1', 3, 4, 1];
var b = a.uniquer();
console.log(b);
[1, 2, "1", 3, 4]