开发者

Jquery find duplicate emails

I want to check for duplicate emails in the list, so I get a list of emails and then not sure how to loop it in order to compare each email in the list..

开发者_开发知识库
var emails = $('td.emails input');
emails.each(function(){

how to compare emails here

});


You can use a hash to track uniqueness. In Javascript, this means an object; try this:

var emails = $('td.emails input');
var found = {};

emails.each(function() {
    var email = $(this).val();

    if (email in found) {
        // duplicate!
    } else {
        found[email] = true;
    }
});


if you need to remove duplicates you can use Jquery Unique


function arrUnique(arr) {
    var o = {}, i, l = arr.length, r = [];
    for(i=0; i<l;i+=1) o[arr[i]] = arr[i];
    for(i in o) r.push(o[i]);
    return r;
};


var emails = $('td.emails input');
var emailArr = [];
emails.each(function(){
     emailArr.push($(this).val());
});

emailArr = arrUnique(emailArr);

Collects all input val that i suppose have the email text and remove duplicates. emailArr is an array with all the emails. You can them convert it back to an array, with emails separated by comma:

alert( emailArr.join(',') );

Unique array function taken from here: http://www.shamasis.net/2009/09/fast-algorithm-to-find-unique-items-in-javascript-array/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜