1

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))
4
  • I'm asking for the best way to express this in javascript. The above line seems a bit crazy, but that's the best I could come up with. Commented Jun 10, 2015 at 1:47
  • I would do shift()/unshift(), the code would look more readable IMHO Commented Jun 10, 2015 at 1:48
  • 2
    Or just skip sorting the first one g.sort(function(a,b) { return a === g[0] ? 0 : a[0].localeCompare(b[0]); }); Commented Jun 10, 2015 at 2:01
  • 1
    jsfiddle.net/w8jkhfr9 Commented Jun 10, 2015 at 2:01

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.