Do you know that there are several ways to deduplicate front-end arrays?

As we all know, front-end array deduplication is a very common problem. Whether you are in project development or going to an interview, this is also a question often asked by interviewers. Therefore, array deduplication is the knowledge we need to master. Those who don’t know how to learn quickly, and those who have already learned it, you are very good. Please go out and learn other knowledge that you don’t know (just kidding, the writing is not good, welcome Big guys leave a message, comment and correct)

1. Use the indexOf() method

First we need to define an empty array, use the indexOf() method to monitor whether an element is contained in the new array, and return the index value, if not, return -1, and add the new element to the new array.

let newArr = [];
for (let i=0;i<arr.length;i++) {
    if (newArr.indexOf(arr[i]) === -1) {
        newArr.push(arr[i]);
    }
}

2. Use the set() method in es6

The set() introduced after es6, the setting of set() itself is a non-repeating class array, so we use this knowledge point to deduplicate the array.

let arr = ['1','2','3','4','5','1','1','9','6','2','3'];
let newArr = new Set(arr);
console.log(newArr); //['1','2','3','4','5','9','6']

3. Using the filter() method

Use the built-in method filter() of the array, filter() combined with indexOf() to find the index for the first time, return all the elements that appear for the first time in the original array, and achieve the effect of deduplication.

let newArr = arr.filter((item, index) => {
    return arr.indexOf(item) === index;
})

Fourth, use includes()

Use the built-in includes() method of the array to monitor whether an element is contained in the array, return true if it is included, and return false if it is not included

let newArr = [];
for (var i=0;i<arr.length;i++) {
    if (!newArr.includes(arr[i])) {
        newArr.push(arr[i]);
    }
}

5. Using the Object object, the key value is the only characteristic

Create an object object and use its unique key value to continuously create attributes in the object. Once an attribute is created, it means that some operations can be performed on the attribute value, and the attribute is already deduplicated. the only element of .

let obj = {}; // 对象的key值是唯一的
let newArr = [];
for (var i=0;i<arr.length;i++) {
    if (!obj[arr[i]]) {
        obj[arr[i]] = arr[i];
    }
}

Guess you like

Origin blog.csdn.net/weixin_44030860/article/details/129026095