3

How to check if array contains a duplicate string , i have validateArray = ['sa','sa','yu'] i have used the following function from SO but same not working for me.

checkDuplicate = function (reportRecipients) {
    if (reportRecipients.length > 1) {
        var recipientsArray = reportRecipients.toString().split(',');
        for (a in recipientsArray) {
            if(reportRecipients.indexOf(a) != reportRecipients.lastIndexOf(a)){
                return true;
                break;
            }
        }
    }
    return false;
}
TurdPile
  • 916
  • 1
  • 7
  • 21
sergioramosiker
  • 375
  • 3
  • 4
  • 19

4 Answers4

27

This is working for me:

var reportRecipients = ['AAA', 'XYZ', 'AAA', 'ABC', 'XXX', 'XYZ', 'PQR'];
var recipientsArray = reportRecipients.sort(); 

var reportRecipientsDuplicate = [];
for (var i = 0; i < recipientsArray.length - 1; i++) {
    if (recipientsArray[i + 1] == recipientsArray[i]) {
        reportRecipientsDuplicate.push(recipientsArray[i]);
    }
}

Hope that helps.

MysticMagicϡ
  • 28,305
  • 16
  • 71
  • 119
0

Take a look at this:

function getDistinctArray(arr) {
    var compareArray = new Array();
    if (arr.length > 1) {
        for (i = 0;i < arr.length;i++) {
            if (compareArray.indexOf(arr[i]) == -1) {
                compareArray.push(arr[i]);
            }
        }
    }
    return compareArray;
}

And here is a working fiddle

Karim AG
  • 2,137
  • 15
  • 29
0

Please try this, if the sort function is not working well :

    var all_list= ['sa','sa','yu'] 
    var duplicates_list = [];
    var unique_list = [];
    $.each(all_list, function(key, value){
            if($.inArray(value, unique_list ) == -1){
                unique_list.push(value);
            }else{
                if($.inArray(value, duplicates_list ) == -1){
                    duplicates_list.push(value);
                }
            }
    });

//duplicated elements 
console.log(duplicates_list )
Flames
  • 949
  • 9
  • 22
-5

just use unique() method.

$.unique(reportRecipients);

https://api.jquery.com/jQuery.unique/

Bhargav Rao
  • 45,811
  • 27
  • 120
  • 136
Aster
  • 1