0

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 has a CSS font-size propriety.

How can I remove the first any from this array that has 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 Answer 1

1

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] );
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

I agree with carefully combining. But I think it's an array of HTML strings, so some parsing is required before comparing id properties.
Thanx, in my code this duplicate all the #IDs. Please let me check it to see where I do it wrong.
I get some "Uncaught TypeError: Cannot call method 'match' of null". Any idea what may cause this?
the first method assumes htmlstring is a valid string. you can add this line to the top of the match method: if(!htmlstring){return;}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.