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
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.
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 .
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.
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:
x == y
x > y
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));
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;
}
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With