sergioramosiker sergioramosiker - 1 month ago 6
jQuery Question

Jquery check if array contains duplicate string

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;
}

Answer

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.

Comments