:: Forum >>

Sort separation of numbers and strings in a column

I'm trying to overwriting the sorting on a column that contains boths numbers and strings so that the strings always appear below the numbers regardless of sort direction. Unfortunately, I'm not having much luck getting it right.

This is what I have so far -
var SpecialSort = AW.Formats.Number.subclass()
...
SpecialSort.create = function()
{
var obj = this.prototype

obj.comparator = function(values, greater, less, equal, error)
{
return function(i, j)
{
try
{
var a = values[i], b = values[j]

if (typeof(a) == "number" && typeof(b) == "number")
{
if (a > b) {return greater}
if (a < b) {return less}
return equal(i, j)
}
if (typeof(a) == "string" && typeof(b) == "string")
return equal(i, j)
if (typeof(a) == "number")
{
return greater == 1 ? greater : less
}
return greater == 1 ? less : greater
}
catch(e){return error(i, j, e)}
}
}
}
...
obj.setCellFormat(new SpecialSort, 7)

Can anyone spot what's wrong with the function?
Anthony
Thursday, September 25, 2008
Are you sure that your numbers are really numbers and not strings like "123" ? Do you get the data from js array?
Alex (ActiveWidgets)
Thursday, September 25, 2008
Hi Alex, yes that's a good point. I'm populating a js array in a CGI script. So they are quoted strings.

Basically the contents of the column are either a numeric value or one other non-numeric value (either "n/a" or blank or somethig else to represent the fact that there's no numeric value. Haven't really decided what to use yet).

When sorting the column, I want to have the non-numeric values always appear below the numeric ones regardless of the sort direction.

Can you suggest the approach I should take for this?
Anthony
Friday, September 26, 2008
You should write numbers to the array without quotes, i.e. 123 and not "123".

Or you can rewrite the comparator function which tries to convert the strings to numbers before comparison.
Alex (ActiveWidgets)
Monday, September 29, 2008
For completeness, here's what I ended up doing.

Since the data was string, I decided to sort it as that. So the code now looks like -
var SpecialSort = AW.Formats.String.subclass()
...
SpecialSort.create = function()
{
var obj = this.prototype

obj.comparator = function(values, greater, less, equal, error)
{
return function(i, j)
{
try
{
var a = values[i], b = values[j]

if (a.indexOf("n/a") < 0 && b.indexOf("n/a") < 0)
{
if (a > b) {return greater}
if (a < b) {return less}
return equal(i, j)
}

if (a.indexOf("n/a") == 0)
{
return greater == 1 ? greater : less
}
return greater == 1 ? less : greater
}
catch(e){return error(i, j, e)}
}
}
}
...
obj.setCellFormat(new SpecialSort, 7)

This sorts the 7th column of my grid, always placing the numeric strings before those with no value (here represented by "n/a") regardless of the sort direction.
Anthony
Friday, October 3, 2008

This topic is archived.


Back to support forum

Forum search