【Javascript基础】数组的操作

数组去重的方式

1、forEach, indexof

let arr = [1, 2, 3, 22, 233, 22, 2, 233, 'a', 3, 'b', 'a'];
        // forEach, indexOf
       Array.prototype.unique = function () {
           const newArray = [];
           this.forEach(item => {
               if (newArray.indexOf(item) === -1) {
                   newArray.push(item);
               }
           });

           return newArray;
       }
console.log(arr.unique())

2、forEach, includes

let arr = [1, 2, 3, 22, 233, 22, 2, 233, 'a', 3, 'b', 'a'];
 Array.prototype.unique = function () {
            const newArray = [];
            this.forEach(item => {
               if (!newArray.includes(item)) {
                   newArray.push(item);
               }
           });

           return newArray;

        }
console.log(arr.unique())

3、sort

let arr = [1, 2, 3, 22, 233, 22, 2, 233, 'a', 3, 'b', 'a'];
Array.prototype.unique = function () {
           const newArray = [];
           this.sort();
           for (let i = 0; i < this.length; i++) {
               if (this[i] !== this[i+1]) {
                   newArray.push(this[i]);
               }
           }

           return newArray;
       }
console.log(arr.unique())

4、map

let arr = [1, 2, 3, 22, 233, 22, 2, 233, 'a', 3, 'b', 'a'];
Array.prototype.unique = function () {
           const tmp = new Map();
           return this.filter(item => {
               return !tmp.has(item) && tmp.set(item, 1)
           })
       }
console.log(arr.unique())

5、set

let arr = [1, 2, 3, 22, 233, 22, 2, 233, 'a', 3, 'b', 'a'];
Array.prototype.unique = function () {
        return [...new Set(this)];
    }
console.log(arr.unique())
posted @ 2021-11-23 10:14  攀登高山  阅读(33)  评论(0编辑  收藏  举报