A
A
Alexey Nikolaev2014-07-11 12:13:01
JavaScript
Alexey Nikolaev, 2014-07-11 12:13:01

How to sort an array by multiple values?

Hello! There is a simple JS code:

vals = vals.sort(
   function(a, b) {return a[1] - b[1]}
);

It sorts a two dimensional array by its second value. But there is one minus: if there are several identical values ​​in the array that follow one after another, for example [12,13,1,1,1], they are skipped by the function, and they must be sorted by a different value, i.e. by a[0]. However, I have absolutely no idea how this can be done using sort(), and is it possible at all?.. Thanks in advance for any help, thanks.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Pavlov, 2014-07-11
@Heian

vals = vals.sort(
   function(a, b) {
     if (a[1] == b[1]) {
       return a[0] - b[0];
     } else return a[1] - b[1];
   }
);

You can simplify and write in one line:
vals = vals.sort(
   function(a, b) { return a[1] == b[1] ? a[0] - b[0] : a[1] - b[1]; }
);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question