简体   繁体   中英

Removing duplicates from FOR statement in Javascript?

I have the following

var ahrefLength = $('a').length;
for (var i = 0; i < ahrefLength; i++) {
    var ahrefUrl = $('a')[i].attr('href');
    if(ahrefUrl != '') {
       $('a')[i].text('Unique');
    }
}

How can I fix this so that no duplicates of "href" appear ? At the moment, if 2 href are the same it fixes both ? ie I need to ensure that no duplicates

var list = {};
$('a[href]').text(function(i,text) {
    var href = $(this).attr('href');
    if( !(href in list) )
        return list[href] = 'Unique';
    else
        ; // what do you want to do with the duplicate?
});

To use a for statement:

var list = {};
var a_els = $('a[href]');  // Cache the DOM selection
var len = a_els.length;

for(var i = 0; i < len; i++) {
    var a_i = a_els.eq(i);
    var href = a_i.attr('href');
    if( !(href in list) )
        a_i.text(list[href] = 'Unique');
    else
        ; // what do you want to do with the duplicate?
}

You can use an associative array (viz., an object) as a sort of "set" to keep track of what URLs you've already seen:

var ahrefLength = $('a').length;
var hrefsToSkip = { '': true };
for (var i = 0; i < ahrefLength; i++) {
    var ahrefUrl = $('a')[i].attr('href');
    if(! hrefsToSkip[ahrefUrl]) {
       $('a')[i].text('Unique');
       hrefsToSkip[ahrefUrl] = true;
    }
}
var hrefIdx = {};
var href = null;
$('a').each(function(i, e) {
  href = $(this).attr('href');
  if ( href != '' && !hrefIdx[href]) {
    $(this).text('Unique');
    hrefIdx[href] = true;
  }
});

Use jQuery slice:)

Demo: http://jsfiddle.net/mhNra/

Remove all duplicates starting from the end

$( "a" ).each( function() {     
     $( "a[href=" + $( this ).attr( "href" ) + "]" ).slice( 0, -1 ).remove()
 });

Remove all duplicates starting from the first anchor

 $( "a" ).each( function() {     
     var arr = $( "a[href=" + $( this ).attr( "href" ) + "]" );
     arr.slice( 1, arr.length  ).remove()
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM