简体   繁体   中英

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

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

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

Another method is to create a value for each array entry, eg 1000*number of votes + candidate number, so that this value is unambiguous and unique, eg we get 1003, 1002, 5, 4, 1. Add a key refering back to the original array and sort.

So we would sort [[1003,0],[1002,1],[5,2],[4,3],[1,4]] by the first element of each subarray.

There is a discrepancy in your sorting system, you use high->low for votes and low-high for candidate number.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM