Home Backend Development PHP Problem What are the 5 methods of deduplicating arrays?

What are the 5 methods of deduplicating arrays?

Jun 10, 2020 am 11:57 AM
Array deduplication

What are the 5 methods of deduplicating arrays?

What are the 5 methods to remove duplicates from arrays?

5 ways to remove duplicates from arrays:

Method 1:

Double for loop Deduplication

Principle: If two pairs are compared, delete the second one

For example: 1 1 1 3 2 1 2 4

Let the first 1 be arr [0] Compare with the following ones one by one. If the following value is equal to arr[0], delete the following value

The result after the first end is 1 3 2 2 4, delete all the following 1

Similarly, the second and third times will delete the same elements as yourself

function noRepeat1(arr){
        // 第一层for用来控制循环的次数
        for(var i=0; i<arr.length; i++){
            //第二层for 用于控制与第一层比较的元素
            for(var j=i+1; j<arr.length; j++){
                //如果相等
                if(arr[i] == arr[j]){
                    //删除后面的 即第 j个位置上的元素  删除个数 1 个
                    arr.splice(j,1);
                    // j--很关键的一步  如果删除 程序就会出错 
                    //j--的原因是 每次使用splice删除元素时 返回的是一个新的数组 
                    // 这意味这数组下次遍历是 比较市跳过了一个元素
                    /*
                        例如: 第一次删除后 返回的是 1 1 3 2 1 2 4
                     *  但是第二次遍历是 j的值为2  arr[2] = 3
                     *  相当于跳过一个元素 因此要 j--
                     * */
                    j--;
 
                }
 
            }
        }
 
        return arr;
    }
Copy after login

Method 2:

Single-layer for loop

Principle Similar to method one

function norepeat(arr){
                arr.sort();
                //先排序让大概相同的在一个位置,这里为什么说是大概相同 是因为sort排序是把元素当字符串排序的 它和可能排成 1 1 10 11 2 20 3 ... 不是我们想要的从小到大
                for(var i = 0; i < arr.length-1;i++){
        //还是两两比较 一样删除后面的
                    if(arr[i]==arr[i+1]){
                        arr.splice(i,1);
                        //i-- 和j--同理
                        i--;
                    }
                }
                return arr;
             }
Copy after login

Method three:

Principle: Use an empty array to store the first appearing element
Use the indexOf attribute indexOf to return a specified The position where the character appears in the string. If not, -1 will be returned.
So we can make good use of this property. When -1 is returned, it will be stored in the array.

function noRepeat2(arr){
        var newArr = [];
        for(var i = 0; i < arr.length; i++){
            if(newArr.indexOf(arr[i]) == -1){
                        newArr.push(arr[i]);
                }
        }
        return newArr;
        }
Copy after login

Method 4:

Principle: Use the idea of ​​​​the object. If there is no such attribute in the object, undefined will be returned.
Use this principle to put it into the array when the returned value is undefined. When assigning a value to this attribute

function norepeat3(arr) {
        var obj = {};
        var newArr = [];
        for(var i = 0; i < arr.length; i++) {
            if(obj[arr[i]] == undefined) {
                newArr.push(arr[i]);
                obj[arr[i]] = 1;
            }
        }
        return newArr;
     }
Copy after login

Method 5:

Principle: If the loop comparison is equal, the value of the following elements will be 0, and finally deleted to 0 during output The premise is that there cannot be 0 in your data, but everything can be flexible. You can set any value to replace this 0. This method was what I thought of implementing at the time, so it was not well optimized.

var newArr = [];
    //控制外循环
    for(var i=0; i<arr.length-1;i++){
        //内存循环 只比较后面的
        for(j=i+1;j<arr.length;j++){
            //如果相等就让其值等于0
            if(arr[i]==arr[j]){
                arr[j]=0;
            }
        }
        //去除值为0的
        if(arr[i]==0){
            continue;
        }else{
            //放入新的数组
            newArr.push(arr[i]);
        }
}
Copy after login

Recommended tutorial: "PHP Video Tutorial"

The above is the detailed content of What are the 5 methods of deduplicating arrays?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Specify the basis for removing duplicate elements when deduplicating PHP arrays Specify the basis for removing duplicate elements when deduplicating PHP arrays Apr 28, 2024 pm 10:48 PM

PHP's array_unique() function is used to remove duplicate elements from an array. By default, strict equality (===) is used. We can specify the basis for deduplication through a custom comparison function: create a custom comparison function and specify the deduplication standard (for example, based on element length); pass the custom comparison function as the third parameter to the array_unique() function. Remove duplicate elements based on specified criteria.

How to implement array deduplication in es5 and es6 How to implement array deduplication in es5 and es6 Jan 16, 2023 pm 05:09 PM

In es5, you can use the for statement and indexOf() function to achieve array deduplication. The syntax "for(i=0;i<array length;i++){a=newArr.indexOf(arr[i]);if(a== -1){...}}". In es6, you can use the spread operator, Array.from() and Set to remove duplication; you need to first convert the array into a Set object to remove duplication, and then use the spread operator or the Array.from() function to convert the Set object back to an array. Just group.

How to maintain key-value correspondence after deduplication in PHP array? How to maintain key-value correspondence after deduplication in PHP array? Apr 27, 2024 pm 12:33 PM

Methods to maintain key-value correspondence after PHP array deduplication include: use the array_unique() function to remove duplicate values, and then use the array_flip() function to exchange key-value pairs. Merge the original array with the deduplicated array, and use the array merging method to retain key-value correspondence.

How to remove duplicates from an array based on specific key-value pairs in PHP? How to remove duplicates from an array based on specific key-value pairs in PHP? Apr 28, 2024 pm 06:18 PM

In PHP, use the array_unique() function to remove duplicates from an array based on specific key-value pairs. When calling the function, pass in the array as a parameter and select the sorting method as the second parameter. This function returns a new array in which duplicates have been removed based on the specified key-value pairs.

Tips for handling empty values ​​and null values ​​when deduplicating PHP arrays Tips for handling empty values ​​and null values ​​when deduplicating PHP arrays Apr 26, 2024 pm 05:03 PM

Tips for handling empty and null values ​​when deduplicating PHP arrays: Use array_unique with array_filter to filter out empty and null values. Use array_unique and define a custom comparison function to treat empty and null values ​​as equal. Use array_reduce to iterate over an array and add items if they do not contain empty or null values.

How to exclude duplicate arrays in PHP How to exclude duplicate arrays in PHP Jun 05, 2023 pm 02:53 PM

Methods to exclude duplicate arrays in PHP: 1. Create a PHP sample file; 2. Define the array to be deduplicated as "$oldArr" and the new array after deduplication as "$newArr"; 3. Use "array_unique()" The function removes duplicate elements from the array and returns the deduplicated array. The code is "$newArr = array_unique($oldArr);" to eliminate duplicate elements. 4. Deduplication can also be performed through a for loop.

How to remove duplicate elements from an array in php How to remove duplicate elements from an array in php May 25, 2023 pm 05:19 PM

How to remove duplicate elements in an array in PHP: 1. Use the "array_unique()" function to remove duplicate data in the array; 2. Traverse through a foreach loop and define a new array to store non-duplicate data to achieve deduplication; 3. Use the array_flip() and array_keys() functions to get the deduplicated array; 4. Use the array_filter() function to deduplicate the original array by using this function combined with an anonymous function.

How to remove duplicates from a javascript array How to remove duplicates from a javascript array Sep 07, 2021 pm 05:59 PM

Method: 1. Use the "[...new Set(arr)]" statement; 2. Use the "Array.from(new Set(arr))" statement; 3. Use the filter and indexOf functions; 4. Use double for loops , check whether the values ​​are duplicated, and use push() to delete them if there are duplicates.

See all articles