JS数组去重

140 阅读1分钟

JS数组去重

  /*
  * 数组去重
  * */
  private uniqueArray (list: any[]) {
    list.forEach((item: any, index1: number) => {
      list.forEach((val: any, index2: number) => {
        if (index1 !== index2 && item === val) {
          list.splice(index2, 1)
        }
      })
    });
    return list;
  }

private uniqueArrary1 () {
var obj = {};
for (var i = 0; i < arr.length; i ++) {
var item = ary[i]; // 以数组值作为属性名
iftypeof obj[item] !== 'undefined'){ // 属性名已经存在
ary[i] = ary[ary.length -1];
ary.length --;
i--;
continue;
}
obj[item] = item;
}
console.log(ary);
  private uniqueArray2 (list: any[]) {
    // 1 1 2 2 3 4
    // 当然你可以自己写快排等nlogn的算法
    list.sort();
    // 剩下的代码和leetcode26题一摸一样

    const size = list.length;
    let slowP = 0;
    for (let fastP = 0; fastP < size; fastP++) {
      if (list[fastP] !== list[slowP]) {
        slowP++;
        list[slowP] = list[fastP];
      }
    }
    return list.slice(0, slowP + 1);
  }