首页 > 其他分享 >js 数组去重

js 数组去重

时间:2022-12-20 15:33:26浏览次数:45  
标签:arr return res len js let 数组 const

利用Set

const res1 = Array.from(new Set(arr));

两层for循环+splice

    const unique1 = arr => {
      let len = arr.length;
      for (let i = 0; i < len; i++) {
        for (let j = i + 1; j < len; j++) {
          if (arr[i] === arr[j]) {
            arr.splice(j, 1);
            // 每删除一个树,j--保证j的值经过自加后不变。同时,len--,减少循环次数提升性能
            len--;
            j--;
          }
        }
      }
      return arr;
    }

利用indexOf

    const unique2 = arr => {
      const res = [];
      for (let i = 0; i < arr.length; i++) {
        if (res.indexOf(arr[i]) === -1) res.push(arr[i]);
      }
      return res;
    }

利用include

    const unique3 = arr => {
      const res = [];
      for (let i = 0; i < arr.length; i++) {
        if (!res.includes(arr[i])) res.push(arr[i]);
      }
      return res;
    }

利用filter

    const unique4 = arr => {
      return arr.filter((item, index) => {
        return arr.indexOf(item) === index;
      });
    }

利用Map

    const unique5 = arr => {
      const map = new Map();
      const res = [];
      for (let i = 0; i < arr.length; i++) {
        if (!map.has(arr[i])) {
          map.set(arr[i], true)
          res.push(arr[i]);
        }
      }
      return res;
    }

过滤唯一值

    const array = [1, 1, 2, 3, 5, 5, 1];
    const uniqueArray = [...new Set(array)];
    console.log(uniqueArray); // Result: [1, 2, 3, 5]

 

标签:arr,return,res,len,js,let,数组,const
From: https://www.cnblogs.com/loveMis/p/16994264.html

相关文章