Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a Multidimensional Array which has 3 columns (by using javascript)

[0] Number of vote
[1] Name of candidate
[2] Candidate Number

My array contents are:

1 | Peter | 3
1 | Mary  | 2
0 | David | 5
0 | John  | 4
0 | Billy | 1

How can I sort the array by [0] Number of vote and then [2] candidate number?

The result should be:

1 | Mary  | 2
1 | Peter | 3
0 | Billy | 1
0 | John  | 4
0 | David | 5
share|improve this question
    
Possible duplicate of : stackoverflow.com/questions/2784230/… –  DhruvPathak Aug 9 '11 at 8:29
    
add comment

4 Answers

up vote 8 down vote accepted

As previously said, you should use a custom sort function. Here's one that would do exactly what you want.

var arr = [];
arr[0] = [1, 'Peter', 3];
arr[1] = [1, 'Mary', 2];
arr[2] = [0, 'David', 5];
arr[3] = [0, 'John', 4];
arr[4] = [0, 'Billy', 1];

arr.sort(function (a,b) {
    if (a[0] < b[0]) return  1;
    if (a[0] > b[0]) return -1;
    if (a[2] > b[2]) return  1;
    if (a[2] < b[2]) return -1;
    return 0;
});
share|improve this answer
add comment
array.sort( function (a,b) {
    if (a[0] > b[0]) return  1;
    if (a[0] < b[0]) return -1;
    if (a[2] > b[2]) return  1;
    if (a[2] < b[2]) return -1;
    return 0;
});
share|improve this answer
add comment

As far as I know you will have to make your own sorting function.
If you can store it in a object than defining a function like in the previous answer will do the job.
Refer Sort array of objects

share|improve this answer
add comment

Here is a generic function

function arraySort(pArray)
{
pArray.sort(
  function(a,b)
  {
    var len=a.length;
    for (var i=0;i<len;i++)
    {
      if (a[i]>b[i]) return 1;
      else if (a[i]<b[i]) return -1;
    }
    return 0;
  }
);
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.