-1

I need to order an array composed by sub-arrays.
The array have to be ordered by the first element of each sub-array element
Example:

myArray = [ [1,0],[3,10],[2,5],[4,0] ]

desired output: [ [1,0],[2,5],[3,10],[4,0] ]

How can I achieve this in Javascript?
Thanks,Nk

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
Nk SP
  • 822
  • 4
  • 19
  • 37

3 Answers3

4
var myArray = [ [1,0],[3,10],[2,5],[4,0] ];    
myArray.sort(); // [[1, 0], [2, 5], [3, 10], [4, 0]]

DEMO
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
1

Use sort

myArray.sort(function(a,b){
    return a[0]-b[0]
})
mguimard
  • 1,881
  • 13
  • 14
-1

This your result

myArray.sort(function(x, y){ return x[0] > y[0] });

use this code hope ,it will work

Demo for this code

Arjun
  • 815
  • 1
  • 8
  • 18
  • Comparison functions should return -1 (negative), 0 or 1 (positive). – Ja͢ck Apr 01 '14 at 08:23
  • you can declare an array ,in your console. myArray = [ [1,0],[3,10],[2,5],[4,0] ], and then write this code you will get your sorted array. myArray.sort(function(x, y){ return x[0] > y[0] }); – Arjun Apr 01 '14 at 08:36
  • A boolean return value may cause unexpected sort results. – Ja͢ck Apr 01 '14 at 08:38
  • i am adding the link in jsfiddle as "Demo for this code",check it once – Arjun Apr 01 '14 at 08:56
  • No,its javascript code which works in any of the javascript compiler,you can check any one of online compiler and give me your output,if you will get any problem,,I hope it will work in any online compiler – Arjun Apr 01 '14 at 09:02