Jquery检查数组是否包含重复的字符串

时间:2014-04-10 06:01:07

标签: jquery arrays

如何检查数组是否包含重复的字符串,我有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;
}

4 个答案:

答案 0 :(得分:20)

这对我有用:

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

希望有所帮助。

答案 1 :(得分:1)

如果排序功能运行不正常,请尝试以下方法:

    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 )

答案 2 :(得分:0)

看看这个:

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

这是 working fiddle

答案 3 :(得分:-3)

只需使用unique()方法。

$.unique(reportRecipients);

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