D3 sorting for multidimensional arrays

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, which leads to a decreasing sort value

 [[12335, 7693, 109313934], [290, 450, 1768064], [1062, 732, 1327754]] 

I am trying to use the d3 method: data.sort(d3.descending);

+8
source share
2 answers

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, since data is a multidimensional array, both a and b will also be arrays. Then

 d3.descending(a[2], b[2]) 

compares the third element in each array so that the results are returned in descending order.

+18
source share

and, if you want to add a secondary view, so that if the values โ€‹โ€‹of the third column are equal, then you will sort by 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]); }; 
+2
source share

All Articles