Taylor Gomez
Taylor Gomez

Reputation: 330

Filter values similar

I want filter values ​​similar, I tried as following js code, but this code can not filter value 111 because this no ,. my html code is as following (Some do, some do not this: ,).

How can fix js code for filter all strings?

DEMO: http://jsfiddle.net/bNuRE/

HTML:

<div class="oo">111</div>
<div class="oo">111, 222, 333</div>
<div class="oo">444, 111</div>
<div class="oo">222, 333</div>
///////////////////////////////////////////////////////
<div class="ww">111</div>
<div class="ww">777</div>
<div class="ww">333</div>
<div class="ww">666</div>

JS:

var valeache = $('.oo').text().split(', ');
$.each(valeache, function (a, val) {
    $('.ww').filter(function () {
        return $(this).text() == val
    }).remove();
});

Upvotes: 0

Views: 55

Answers (3)

Scott Sauyet
Scott Sauyet

Reputation: 50787

It's not entirely clear to me what you're trying to do. Are you simply trying to remove the elements from the target list whose value match one of the (possibly comma-separated) values from any of the elements of the source list? If so, I think you can do it more easily:

var vals = $.map($('.oo'), $.text).join(", ").split(", ");

$('.ww').filter(function () {
    return $.inArray($(this).text(), vals) > -1;
}).remove();

Demo: http://jsfiddle.net/CrossEye/MVGLQ/1/

That initial array contains duplicates, but that shouldn't be a problem.

Upvotes: 0

Alexander
Alexander

Reputation: 23537

Your construction of valeache is wrong.

You need to iterate over each .oo element to correctly construct valeache.

var valeache = $('.oo').map(function(){
    return $(this).text().split(', ');
}).get();
$.each(valeache, function (a, val) {
    $('.ww').filter(function () {
        return $(this).text().trim() == val;
    }).remove();
});

Upvotes: 1

thecodeparadox
thecodeparadox

Reputation: 87073

var valeache = null;

$('.oo').text(function(i, text) {
    valeache += text.replace(/\s/g,'') + ',';
})
valeache = $.unique( valeache .replace(/,$/,'').split(',') );

$.each(valeache, function (a, val) {
    $('.ww').filter(function () {
        return $(this).text() == val
    }).remove();
});

Demo: http://jsfiddle.net/xfSK4/3/

Upvotes: 0

Related Questions