[JS] 3 most common and simplest array deduplication methods

  1. Set collection deduplication

Use the unique feature of the value in the set collection to deduplicate

let uniqueArr = [...new Set(arr)]

  1. Use filter and indexOf methods to remove duplicates

The filter method filters out a new array; the indexOf method obtains the subscript of an element that appears for the first time in the array, and in the [1,2,1,2] array, the subscript that obtains the element 1 is always 0, and the combination of the two You can filter out all the elements that appear for the first time.

let arr1 = [1,2,3,4,1,2,3,3];
let uniqueArr = arr1.filter((item,index,originArr)=>{
    return originArr.indexOf(item) == index
})
console.log(uniqueArr);

3. Use the object key value to deduplicate

There is only one key value for an object, use this feature to deduplicate

let arr1 = ['ko', 'ko', 1, 2, 3, 4, 1, 2, 3, 3];
let o = {}
    arr1.forEach(val => {
    o[val] = 'xxx' //属性值随意
})
let uniqueArr = Object.keys(o)
console.log(uniqueArr);

Guess you like

Origin blog.csdn.net/Andye11/article/details/129109037