sorting javascript array slice

3.6k views Asked by At

In trying to create a sortable table, I am sorting the underlying array of data:

var g = [
   [ 'First Name', 'Last Name', 'Id', 'Age'],
   [ 'Joe', 'Blogs', '1', 24],
   [ 'Fred', 'Frog', '2', 18],
];

I want to sort everything except the header.

g = g.sort(mycomparison);

is no good, though I could change the comparison routine to always put element[0] in front of everything else.

Instead, I would like to sort everything except the header. The following seems to do what I want, but I wanted to know if there is a better way to express this in javascript. I want to sort the last n-1 elements.

g = g.slice(0,1).concat(g.slice(1,g.length-1).sort(mycomparison))
1

There are 1 answers

0
TaoPR On BEST ANSWER

If you are interested in another way which looks a bit tidier, see this following underscore.js way:

g =  [].concat(_.first(g), _sort(_.tail(g), mycomparison ));

Using underscore does not help improving performance but it just simplifies and makes your code a bit more readable. From the example above, I believe it makes sense to people who even don't usually use underscore.

It's straightforward and semantic so people read it and understand instantly that it splits the first, and the rest of array g, sort the rest and re-join them. (To me it looks more readable than vanilla JavaScript)