Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Sort Multidimensional Array

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
like image 864
Joe Yan Avatar asked Aug 09 '11 08:08

Joe Yan


People also ask

Can you sort a multidimensional array?

Sorting a multidimensional array by element containing date. Use the usort() function to sort the array. The usort() function is PHP builtin function that sorts a given array using user-defined comparison function.

How do you sort a multidimensional list?

Use sorted() with a lambda function to sort a multidimensional list by column. Call sorted(iterable, key=None) with key set to a lambda function of syntax lambda x: x[i] to sort a multidimensional list iterable by the i th element in each inner list x .

How do you sort a matrix in JavaScript?

Approach: Create a temp[] array of size n^2. Starting with the first row one by one copy the elements of the given matrix into temp[]. Sort temp[]. Now one by one copy the elements of temp[] back to the given matrix.


2 Answers

To sort a multi-dimensional array comparing by coordinate 0 first and then by component 2 you can combine two compare functions with ||:

compare 0-coordinates || compare 2-coordinates

For numeric values simply use a difference as a compare function, as x - y is:

  • 0 if x == y
  • >0 if x > y
  • <0 if x < y

Adjust the order of the elements in the differences to take care of ascending/descending order.

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

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

console.log(JSON.stringify(myArray));
like image 138
user2314737 Avatar answered Sep 21 '22 11:09

user2314737


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;
  }
);
}
like image 42
Nilesh Avatar answered Sep 22 '22 11:09

Nilesh