如何检查数组是否包含重复字符串,我使用过 validateArray = ['sa','sa','yu']
来自 SO 的以下功能,但同样不适用于我。

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

最佳答案

这对我有用:

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

希望有帮助。

关于Jquery 检查数组是否包含重复的字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22979762/

10-11 16:08