9 ways to deduplicate js array

  1. Double for loop deduplication
// 双重for循环
    const arr = [1, 2, 1, 5, 2, 1, 3, 9, 6, 5, 7, 7, 7, 2, 7, 10, 10];
    let arrNew = [arr[0]];

    for (const i in arr) {
    
    
      let flag = false;
      for (const j in arrNew) {
    
    
        if (arrNew[j] === arr[i]) {
    
    
          flag = true;
          break;
        }
      }
      flag ? arrNew : arrNew.push(arr[i]);
    }

    console.log(arrNew);
  1. sort sort deduplication
// sort
    const arr1 = [1, 2, 1, 5, 2, 1, 3, 9, 6, 5, 7, 7, 7, 2, 7, 10, 10];
    function dRemoval(params) {
    
    
      const arrNew1 = params.sort((a, b) => a - b);
      let res = [arrNew1[0]];

      for (let i = 1; i < arrNew1.length; i++) {
    
    
        if (arrNew1[i] !== arrNew1[i - 1]) {
    
    
          res.push(arrNew1[i]);
        }
      }

      return res;
    }

    console.log(dRemoval(arr1));
  1. According to the characteristics of the existence of object attributes to deduplication
// 根据对象属性存在的特点来去重
    const arr2 = [1, 2, 1, 5, 2, 1, 3, 9, 6, 5, 7, 7, 7, 2, 7, 10, 10];
    let arrNew2 = [];
    let obj = {
    
    };

    for (let i = 0; i < arr2.length; i++) {
    
    
      if (!obj[arr2[i]]) {
    
    
        obj[arr2[i]] = 1;
        arrNew2.push(arr2[i]);
      }
    }

    console.log(arrNew2);
  1. indexOf deduplication
// indexOf
    const arr3 = [1, 2, 1, 5, 2, 1, 3, 9, 6, 5, 7, 7, 7, 2, 7, 10, 10];
    let arrNew3 = [];

    for (const i in arr3) {
    
    
      if (arrNew3.indexOf(arr3[i]) === -1) {
    
    
        arrNew3.push(arr3[i]);
      }
    }

    console.log(arrNew3);
  1. includes deduplication
// includes
    const arr4 = [1, 2, 1, 5, 2, 1, 3, 9, 6, 5, 7, 7, 7, 2, 7, 10, 10];
    let arrNew4 = [];

    for (const i in arr4) {
    
    
      if (!arrNew4.includes(arr4[i])) {
    
    
        arrNew4.push(arr4[i]);
      }
    }

    console.log(arrNew4);
  1. reduce deduplication
// reduce
    const arr5 = [1, 2, 1, 5, 2, 1, 3, 9, 6, 5, 7, 7, 7, 2, 7, 10, 10];
    let arrNew5 = [];

    arr5.reduce((pre, cur, index, arr) => {
    
    
      arrNew5.includes(cur) ? arrNew5 : arrNew5.push(cur);
    }, 0);

    console.log(arrNew5);
  1. Set deduplication
// Set
    const arr6 = [1, 2, 1, 5, 2, 1, 3, 9, 6, 5, 7, 7, 7, 2, 7, 10, 10];
    let arrNew6 = Array.from(new Set(arr6));
    console.log(arrNew6);
  1. splice deduplication
// splice
    const arr7 = [1, 2, 1, 5, 2, 1, 3, 9, 6, 5, 7, 7, 7, 2, 7, 10, 10];
    for (let i = 0; i < arr7.length; i++) {
    
    
      for (let j = 1 + i; j < arr7.length; j++) {
    
    
        if (arr7[i] === arr7[j]) {
    
    
          arr7.splice(j, 1);
          j--;
        }
      }
    }

    console.log(arr7);

Guess you like

Origin blog.csdn.net/qq_45488467/article/details/128936154