-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

2

3 Answers 3

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

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

Comments

1

Use sort

myArray.sort(function(a,b){
    return a[0]-b[0]
})

1 Comment

Note that this will yield unexpected sort results if the operands are not integer values.
-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

5 Comments

Comparison functions should return -1 (negative), 0 or 1 (positive).
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] });
A boolean return value may cause unexpected sort results.
i am adding the link in jsfiddle as "Demo for this code",check it once
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.