Use js to realize the method of removing duplicate elements from an array

method 1:

Two layers of for loops, to determine whether the elements of the first layer and the second layer are the same, delete the element splice (start position, 1) if they are the same, 0 means add

let arr = ['a', 'b', 'c', 'qq', 'b', 'qq', 'wx', 1, 2, 1, 2];
console.log(arr);
      //两层for循环,判断第一层和第二层的元素是否相同,相同就删除元素splice(开始位置,1),0代表添加
        function norepeat(arr) {
            for (let i = 0; i < arr.length; i++) {
                for (let j = i + 1; j < arr.length; j++) {
                    if (arr[i] == arr[j]) {//下标相同则删除该值
                        arr.splice(j, 1);//后面的元素会自动补位,需要比较一次j所在位置的元素,所以需要使j自减
                        j--;
                    }
                }
            }
       return arr;
     }
console.log(norepeat(arr));

Show results:

Method 2:

The set() method in es6

The main function of set in es6 is to deduplicate the array, set() instantiates the deduplication of the array, and secondly to merge and subtract the array

The Array.from() method can convert the Set structure into an array, another method to remove repeated members of the array

let arr = ['a', 'b', 'c', 'qq', 'b', 'qq', 'wx', 1, 2, 1, 2];
console.log(arr);
let newarr1 = new Set(arr);
console.log(newarr1);
//Array.from()方法可以将 Set 结构转为数组,去除数组重复成员的另一种方法
let newarr2 = Array.from(new Set(arr));
console.log(newarr2);

Show results:

 Method 3:

indexof() finds strings:

Traverse the array that needs to be deduplicated to determine whether there is a current element in the new array, and if not, add (push) the value into the new array

indexOf() case-sensitive return value: -1 means no matching substring found

let arr = ['a', 'b', 'c', 'qq', 'b', 'qq', 'wx', 1, 2, 1, 2];
console.log(arr);
function newArr(arr) {
            let newarr4 = [];    //新数组
            for (let i = 0; i < arr.length; i++) {
                if (newarr4.indexOf(arr[i]) == -1) {    //判断新数组中是否有当前元素,为-1就是没有该值,最后将值添加(push)进新数组中
                    newarr4.push(arr[i]);
                }

            }
            return newarr4;
        }
console.log(newArr(arr));

Show results:

 Method 4:

The filter() method removes duplicate elements, and the indexof() finds strings

filter()方法会创建一个新数组,原数组的Each element is passed into the callback function, and the callback function has a return return value. If the return value is true, the element will be saved in the new array; if the return value is false, the element will not be saved in the new array; the original array will not changes happened.

let arr = ['a', 'b', 'c', 'qq', 'b', 'qq', 'wx', 1, 2, 1, 2];
console.log(arr);
let newarr3 = arr.filter(function (ele, index) {
            return arr.indexOf(ele) == index;
        });
console.log(newarr3);

The results show that:

filter() analysis:

 

Guess you like

Origin blog.csdn.net/qq_64180670/article/details/128279150