views:

60

answers:

1

I have the following dynamically generated arrays:

,<div id="layer0" style="left: 470px; top: 286px;">Some Text</div>
,<div id="layer0" style="font-size: 68px; left: 70px; top: 286px; ">SomeText</div>
,<div id="layer1" style="font-size: 18px; left: 60px; top: 286px; ">SomeText</div>
,<div id="layer2" style="font-size: 18px; left: 50px; top: 286px; ">SomeText</div>

The first 2 entries are not exactly duplicates but have the same "id": layer0. The second one is different because it have a css font-size propriety.

How can I remove the first any from this array that have a duplicate "id" but may differ in the exact form.

The arrays are combined together trough:

var allcode = $.merge([oldarray],[newarray]) 

Where in oldarray are some duplicates I need to get rid of. Thank you.

+1  A: 

I think you'd be ahead to more carefully combine the arrays, rather than mash them together and clean up later.

function matchId(htmlstring){
    var match = htmlstring.match( new RegExp(/id=\"([^\"]+)\"/i) ); 
    if (match && match[1]) {
        return match[1];
    }
    return '';
}

for (var j=0; j < oldarray.length; j++) {

    var exists = false;

    for (var k=0; k < newarray.length; k++) {

        var newId = matchId(newarray[k]);
        var oldId = matchId(oldarray[j]);

        if (newId == oldId) {
            // element already exists.
            exists=true;
            break;
        }
    }

    if (!exists) {
        newarray.push( oldarray[j] );
    }
}
lincolnk
I agree with carefully combining. But I think it's an array of HTML strings, so some parsing is required before comparing id properties.
Matthew Flaschen
that's a good point, i'll fix it up.
lincolnk
Thanx, in my code this duplicate all the #IDs. Please let me check it to see where I do it wrong.
Mircea
Sorry, it was from my end. It works now. Thank you!
Mircea
I get some "Uncaught TypeError: Cannot call method 'match' of null". Any idea what may cause this?
Mircea
the first method assumes `htmlstring` is a valid string. you can add this line to the top of the match method: `if(!htmlstring){return;}`
lincolnk