Seven ways to remove duplicates from JavaScript arrays

Here are several methods for deduplicating arrays:

Array deduplication method 1: Use Set collection to deduplicate

//方法一:
function fun(arr){
    let set = new Set(arr);
    arr=Array.from(set);
    return arr;
}

Array deduplication method 2: Create a new array, add array elements without duplicates to the new array and return the new array 

//方式二
    function fun(arr) {
        let arr1 = [];
        for (let i = 0; i < arr.length; i++) {
            if (arr1.indexOf(arr[i]) > -1) {
                continue;
            } else {
                arr1.push(arr[i]);
            }
        }
        return arr1;
    }

Array deduplication method three: Traverse the array to determine and delete duplicate elements 

   //方式三:
    function fun(arr){
    	for(let i = 0;i<arr.length;i++){
    		for(let j = i+1;j<arr.length;){
    			if(arr[i]==arr[j]){
    				arr.splice(j,1)
    			}else{
    				j++
    			}
    		}
    	}
    	return arr;
    }

Array deduplication method 4: Use the array filter method to filter out array elements that only appear once 

//方法四:
    function fun(arr){
    	return arr.filter((item,index)=>arr.indexOf(item)==index);
    }

Array deduplication method 5: By comparing the subscript of the first occurrence of the element with the subscript of the last occurrence of the element, if the following table is not equal, it means duplication, delete one, and then ++

//    方法五:
    function fun(arr){
    	for(let i=0;i<arr.length;){
    		if(arr.indexOf(arr[i])!=arr.lastIndexOf(arr[i])){
    			arr.splice(i,1)
    		}else{
    			i++
    		}
    	}
    	return arr;
    }

Array deduplication method 6: First use the sort() method to sort the array, and then compare adjacent elements in sequence to see if they are equal. If they are equal, delete the following elements.

function fun(arr){
    arr.sort();
    for(let i = 0; i < arr.length-1; i++) {
      if(arr[i] === arr[i+1]) {
        arr.splice(i+1, 1);
        i--;
      }
    }
    return arr;
}

 

Array deduplication method 7: Use the reduce() method to traverse the array and store the array elements into a new array. If the element already exists in the new array, it will not be stored again.

function fun(arr) {
  return arr.reduce((prev, cur) => {
    if(!prev.includes(cur)) {
      prev.push(cur);
    }
    return prev;
  }, []);
}
 

Extended array splice method: 

Extended array reduce method:

The reduce() method of an array is a higher-order function used to accumulate all elements in the array. It receives two parameters: a callback function and an initial value. The callback function contains 4 parameters:

  • accumulator: Accumulator, which stores the result of the last callback function execution (that is, the accumulated value).
  • currentValue: The current element, that is, the element currently being processed in the array.
  • currentIndex: The index of the current element.
  • array: current array.

The reduce() method calls the callback function sequentially for each element in the array, adds the return value of the callback function to the accumulator, and returns the final result.

The following is the syntax of the reduce() method:

array.reduce(callback[, initialValue]);

Among them, callback is required and is the callback function, and initialValue is optional and is the initial value.

Here is an example that calculates the sum of all elements of an array:

let arr = [1, 2, 3, 4, 5];
let sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 15

        In the above example, the initial value is 0, the callback function adds the accumulator and the current element, and the result is assigned to the accumulator. Therefore, the final result is 15.

        It should be noted that if the array is empty and no initial value is provided, the reduce() method will throw a TypeError exception. If the array has only one element (regardless of whether an initial value is provided), then that element is the return value. If the array is empty but an initial value is provided, the initial value is the return value.


The above are seven ways of deduplicating arrays compiled by me. If there are other ways, you are welcome to discuss them.

Guess you like

Origin blog.csdn.net/weixin_40381947/article/details/131389669