Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3 sort descending for multi-dimensional arrays

Tags:

d3.js

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

like image 829
Tom Avatar asked Oct 17 '13 00:10

Tom


People also ask

Can you sort a 2D array?

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.

What does D3 ascending do?

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.

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

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.

like image 171
mdml Avatar answered Oct 14 '22 16:10

mdml


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]);
};
like image 33
keithpjolley Avatar answered Oct 14 '22 15:10

keithpjolley