data = [[1062, 732, 1327754], [12335, 7693, 109313934], [290, 450, 1768064]];
how can I sort by the third value of each array object in my data resulting in the descending sort value of
[[12335, 7693, 109313934], [290, 450, 1768064], [1062, 732, 1327754]]
I am trying to use the d3 method:
data.sort(d3.descending);
In a 2D array, a cell has two indexes one is its row number, and the other is its column number. Sorting is a technique for arranging elements in a 2D array in a specific order. The 2D array can be sorted in either ascending or descending order.
ascending() function in D3. js is a built-in comparator function for the natural order which accepts two parameters and computes their natural order. Parameters: This function accepts two parameters x, y whose natural order needs to be computed.
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.
You need to pass data.sort
a comparison function that will access the third element in each array:
data.sort(function(a, b){ return d3.descending(a[2], b[2]); })
Here because data
is a multi-dimensional array, both a
and b
will be arrays as well. Then
d3.descending(a[2], b[2])
performs the comparison of the third element in each array such that the results are returned in descending order.
and, if you want to add in a secondary sort so that if the third column values are equal you then sort on the second column:
data.sort(function(a, b) {
if(a[2]===b[2]) {
return d3.descending(a[1], b[1]);
}
return d3.descending(a[2], b[2]);
};
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