-1

I'm using Nick Grealy's amazingly terse table sorter (Sorting HTML table with JavaScript), but it doesn't properly sort columns that are dollar amounts {$199, $23, $46} or columns that are percentages {10%, 3%, 5%}; the largest values are improperly sorted to the top because the algo is doing a text sort, because the values contain non-numeric chars (% and $).

I understand the general idea of fixing that: strip out any $ or % signs, and then sort on the result (which will be numeric). My problem is that Grealy's code is way over my head and I don't see how to edit it. I tried this:

const comparer = (idx, asc) => (a, b) => ((v1, v2) => 
    v1=v1.replace(/[$%]/,''); // << My addition
    v2=v2.replace(/[$%]/,''); // << My addition
    v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2)
    )(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));

But that gives a syntax error. I spent some time studying arrow functions and curried functions but it's pretty confusing even for simple examples, and Grealy's code is more complex than that (e.g., the extra ( before (v1,v2) that doesn't get resolved until several lines later. How can I modify the code to sort $ and % values properly?

1 Answers1

1

If you write multiline functions, you need to use braces.

const comparer = (idx, asc) => (a, b) => ((v1, v2) => {
  v1 = v1.replace(/[$%]/,'');
  v2 = v2.replace(/[$%]/,'');
  return v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2)
})(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));

*updated code

TheWuif
  • 988
  • 6
  • 11