I thought I had this figured out but I was wrong. I’m experiencing a strange issue with sorting the key string ending with a number/digit. When I sort my data to display from highest (newest item added) to the lowest (oldest item added); it seems to sort the key string with the single numbers on top as a group, then the multiple digit numbers will underneath the single numbers. When a new location is added (new one or adding another existing location the array returns random sequence results; not adhering to the sort order, from newest to the oldest. I tried many sort methods, it will sorts but I get the same results mentioned. Below is the code I’m using to show the different location and its number of time it’s listed.
My data array from the console. I am fetching the data from a SharePoint list.
Array(16) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
0: Object { key: "Location-9", values: 1 }
1: Object { key: "Location-8", values: 5 }
2: Object { key: "Location-7", values: 5 }
3: Object { key: "Location-6", values: 5 }
4: Object { key: "Location-5", values: 14 }
5: Object { key: "Location-4", values: 10 }
6: Object { key: "Location-3", values: 8 }
7: Object { key: "Location-2", values: 6 }
8: Object { key: "Location-16", values: 5 }
9: Object { key: "Location-15", values: 2 }
10: Object { key: "Location-14", values: 2 }
11: Object { key: "Location-13", values: 2 }
12: Object { key: "Location-12", values: 2 }
13: Object { key: "Location-11", values: 2 }
14: Object { key: "Location-10", values: 2 }
15: Object { key: "Location-1", values: 15 }
My script for counting the number of times the Location was added to the SharePoint list:
data = chartData;
data.sort(function (a, b) { return b.key < a.key ? -1 : 1;})
var LocationCount = d3.nest().key(function(d) { return d.value; })
.rollup(function(v) { return v.length; })
.entries(data);
2
Answers
You can extract the numeric value of the key and sort by it. The extraction during sorting seems to work faster: