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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22979762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 02:08:48  来源:igfitidea点击:

Jquery check if array contains duplicate string

jqueryarrays

提问by sergioramosiker

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.

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

回答by MysticMagic?

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.

希望有帮助。

回答by Midhun1993

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 )

回答by Karim AG

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

这是一个工作小提琴

回答by Aster

just use unique() method.

只需使用 unique() 方法。

$.unique(reportRecipients);

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

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