Aw Qirui Guo Aw Qirui Guo - 1 month ago 10
Javascript Question

How to sort a table via complicated rules

I have a table like this:

a-1/1 1.1
a-2/3 2.3
a-1/3 1.3
a-10/1 10.1
a-10/2 10.2
a-2/1 2.1
a-1/2 1.2
a-2/2 2.2
..


I need to sort it into something like this:

a-1/1 1.1
a-1/2 1.2
a-1/3 1.3
a-2/1 2.1
a-2/2 2.2
a-2/3 2.3
..
a-10/1 10.1
a-10/2 10.2
a-10/3 10.3


The tough things in this case:


  1. I am sorting a table

  2. I am sorting the table with a part, rather than the value itself, in the column.


Answer
var data =
['a-1/1    1.1',
 'a-2/3    2.3',
 'a-1/3    1.3',
 'a-10/1   10.1',
 'a-10/2   10.2',
 'a-2/1    2.1',
 'a-1/2    1.2',
 'a-2/2    2.2'];

data.sort(function (f, s) {
    var one = parseFloat(f.split(/\s+/)[1]), two = parseFloat(s.split(/\s+/)[1]);
    return one === two ? 0 : one > two ? 1 : -1;
});

console.log(data);

Output

[ 'a-1/1    1.1',
  'a-1/2    1.2',
  'a-1/3    1.3',
  'a-2/1    2.1',
  'a-2/2    2.2',
  'a-2/3    2.3',
  'a-10/1   10.1',
  'a-10/2   10.2' ]
Comments