Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Array Sorting Question 1

Status
Not open for further replies.

Mighty

Programmer
Feb 22, 2001
1,682
0
0
US
Guys,

Is it possible when sorting an array to remove duplicate entries.

i.e.
if (a > b) return 1
else if (a < b) return -1
else remove a from array; Mise Le Meas,

Mighty :)
 
You could put a filter routine in front of the call to sort() or reverse() to remove the duplicates. Removing elements in the sort is going to give you problems because the script-engine is building a new array based on your return values but I guess you could avoid that problem by scattering your latter array references with null checks ;->
 
Sample code:
Code:
function unique() {
    var seen = new Object;
    var uniq = new Array;

    for( var i = 0; i < this.length; i++ ) {
        if( ! seen[ this[i] ] ) {
            seen[ this[i] ] = true;
            uniq[ uniq.length ] = this[i];
        }
    }
    return uniq.sort();
}

Array.prototype.unique = unique;

var a = [ 1, 2, 2, 4, 5, 2, 2, 3, &quot;a&quot;, &quot;b&quot;, &quot;a&quot; ];
var b = a.unique();

for( var j = 0; j < b.length; j++ )
    alert( j + &quot;: &quot; + b[j] );
Cheers, Neil
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top