The Zurich release has arrived! Interested in new features and functionalities? Click here for more

How to get the duplicate values from array

Santhosh23
Tera Expert

Hi all can someone please let me know how to get the duplicate value from array. I do have one variable which will store the list of values in array. I need to get only the duplicate values and store the duplicate value in another variable

1 REPLY 1

Filipe Cruz
Kilo Sage
Kilo Sage

Hello Santhosh,

Here is a function that you can use to get the duplicate values:

var arr = ["a", "b", "c", "a", "b", "d", "e", "a"];

toFindDuplicates(arr);

function toFindDuplicates(arry) {
    var duplicates = [];
    var resultToReturn = false;
    for (var i = 0; i < arry.length; i++) { // nested for loop
        for (var j = 0; j < arry.length; j++) {
            // prevents the element from comparing with itself
            if (i !== j) {
                // check if elements' values are equal
                if (arry[i] === arry[j]) {
                    // duplicate element present                                
                    duplicates.push(arry[i]);
                    
                }
            }
        }
       
    }
    var au = new ArrayUtil();
     gs.print(au.unique(duplicates).join(","));
     return au.unique(duplicates);
}

 

In this example the output will be:

*** Script: b,a

 

Do the tuning in the output.

Please, don't forget to mark my answer as correct if it solves your issue or mark it as helpful if it is relevant for you!

Best Regards,

Filipe Cruz