Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
63
rated 0 times [  66] [ 3]  / answers: 1 / hits: 31443  / 13 Years ago, tue, august 9, 2011, 12:00:00

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

More From » arrays

 Answers
54

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;
});

[#90722] Monday, August 8, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
isaac

Total Points: 645
Total Questions: 109
Total Answers: 96

Location: Cayman Islands
Member since Fri, Mar 4, 2022
2 Years ago
;