jQuery的检查,如果数组包含重复的字符串 [英] Jquery check if array contains duplicate string

查看:282
本文介绍了jQuery的检查,如果数组包含重复的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查数组包含重复的字符串,我有validateArray = ['山','玉''山']我已经使用
下面的函数从左右,但同样不是为我工作。

  checkDuplicate =功能(reportRecipients){
    如果(reportRecipients.length→1){
        。VAR recipientsArray = reportRecipients.toString()分('');
        对于(一个在recipientsArray){
            如果(reportRecipients.indexOf(一)!= reportRecipients.lastIndexOf(一)){
                返回true;
                打破;
            }
        }
    }
    返回false;
}


解决方案

这是为我工作:

  VAR reportRecipients = ['AAA','某某','AAA','ABC','XXX','某某','PQR'];
变种recipientsArray = reportRecipients.sort();变种reportRecipientsDuplicate = [];
对于(VAR I = 0; I< recipientsArray.length - 1;我++){
    如果(recipientsArray第[i + 1] == recipientsArray [I]){
        reportRecipientsDuplicate.push(recipientsArray [I]);
    }
}

希望有所帮助。

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

解决方案

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.

这篇关于jQuery的检查,如果数组包含重复的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆