Eight methods of JS to achieve array deduplication (practical)

foreword

js array deduplication is one of the more common array operation methods. There are many blog articles about array deduplication on the Internet. There are various methods, but some methods are not practical and can easily cause unnecessary troubles, so we need To get rid of the dross and get the essence, let's sort out some more practical array deduplication methods.

Methods 1: Using double for loops

Idea: Define a new array and store the first element of the original array, then compare the element groups one by one with the elements of the new array, and store them in the new array if they are different.

function unique(arr) {
    let newArr = [arr[0]];
    for (let i = 1; i < arr.length; i++) {
        let repeat = false;
        for (let j = 0; j < newArr.length; j++) {
            if (arr[i] === newArr[j]) {
                repeat = true;
                break;
            }
        }
        if (!repeat) {
            newArr.push(arr[i]);
        }
    }
    return newArr;
}

console.log(unique([1, 1, 2, 5, 5, 3, 4, 9, 6, 3, 4]));
// 结果是[1, 2, 5, 3, 4, 9, 6]

Methods 2: Using Objects

Idea: Take advantage of the existing characteristics of object properties, if there is no such property, store it in a new array

function unique(arr) {
    const newArr = []
    const obj = {}
    arr.forEach(item => {
      if (!obj[item]) {
        newArr.push(item)
        obj[item] = true
      }
    })
  
    return newArr
  }
  
  console.log(unique([1, 1, 2, 5, 5, 3, 4, 9, 6, 3, 4])) 
  // 结果是[1, 2, 5, 3, 4, 9, 6]

Methods 3: Use the indexOf method of the array

Idea: Create an empty array, traverse the array that needs to be deduplicated, and store the array elements in the new array. Before storing, determine whether the array already contains the current element, and if not, store it. This method also fails to NaNdeduplicate.

var arr = [1,9,8,8,7,2,5,3,3,3,2,3,1,4,5,444,55,22];
function unique(arr) {
       //定义一个新的临时数组 
       var newArr=[]; 
       //遍历当前数组 
       for(var i=0;i<arr.length;i++) {
         //如果当前数组的第i已经保存进了临时数组,那么跳过,
         //否则把当前项push到临时数组里面 
         if(newArr.indexOf(arr[i]) === -1) {  
//indexOf() 判断数组中有没有字符串值,如果没有则返回 -1 
            newArr.push(arr[i]);
         }
       }
   return newArr
 }
 var arr2 = unique(arr);
 console.log(arr2);  
//[ 1, 9, 8, 7, 2, 5, 3, 4, 444, 55, 22]

Methods 4: Use the includes method of the array

Idea: The logic of this method is similar to that of the indexOf method, except that the includes method is used to determine whether duplicate elements are included.

function unique(arr) {
    var newArr = []
    for (var i = 0; i < arr.length; i++) {
        if (!newArr.includes(arr[i])) {
            newArr.push(arr[i])
        }
    }
    return newArr
}
console.log(unique([1,5,1,5,3,74,32,7,32,6,9,4,7,4]));
// 结果是[1, 5, 3, 74, 32, 7, 6, 9, 4]

Methods 5: Using the filter and includes methods of arrays

Similarly, filter+indexOf can also

function unique(arr) {
    var newArr = []
    newArr = arr.filter(function (item) {
        return newArr.includes(item) ? '' : newArr.push(item)
    })
    return newArr
}
console.log(unique([1,5,1,5,3,74,32,7,32,6,9,4,7,4]));
// 结果是[1, 5, 3, 74, 32, 7, 6, 9, 4]

Methods 6: Using the array's forEach and includes methods

function unique(arr) {
    let newArr = [];
    arr.forEach(item => {
        return newArr.includes(item) ? '' : newArr.push(item);
    });
    return newArr;
}
console.log(unique([1,1,2,5,6,3,5,5,6,8,9,8]));
// 结果是[1, 2, 5, 6, 3, 8, 9]

Methods 7: Use the splice method of the array.

function unique(arr){
    for(var i=0;i<arr.length;i++){
        for(var j=i+1;j<arr.length;j++){
            if(arr[i]==arr[j]){ 
            //如果第一个等于第二个,splice方法删除第二个
            arr.splice(j,1);
            j--;
            }
        }
    }
    return arr;
}
 
var arr = [1,1,2,5,6,3,5,5,6,8,9,8];
 
console.log(unique(arr))
//[ 1, 2, 5, 6, 3, 8, 9 ]

Methods 8: Use Set() + Array.from()

The code is the most concise, principle:

  • SetObject: is a collection of values ​​whose elements you can iterate over in the order they were inserted . The elements in the Set will only appear once , that is, the elements in the Set are unique .
  • Array.from() Method: Create a new, shallow copy of an Array instance of an Array-like or Iterable object .
function unique(arr){
    return Array.from(new Set(arr))
}
 
var arr = [1,1,2,9,6,9,6,3,1,4,5];
 
console.log(unique(arr))
//[ 1, 2, 9, 6, 3, 4, 5 ]

Guess you like

Origin blog.csdn.net/m0_65335111/article/details/127720276