sorting - d3.js sort descending positive to negative -
would sort largest positive largest negative.
desired output: (3,2,1,0,-1,-2,-3), current output: (3,2,1,0,-3,-2,-1)
initial array:
["-0.87", "0.51", "3.34", "1.58", "2.67", "0.51", "-1.58", "1.91", "-0.86", "-0.42", "0.23", "1.5", "-1.67", "1.9", "-2.88", "-0.63", "1.13", "-1.37", "-0.42", "-0.35", "-0.38", "0.65", "-0.41", "0.49", "1", "-0.14", "-0.07", "2.41", "3.09", "0.85", "0.51", "-0.67", "0.53", "0.98", "-0.88", "0.18", "-0.75", "-0.22", "-0.27", "-2.09", "0.01", "1.14", "-0.64", "-0.53", "3.01", "1.49", "1.56", "0", "0.67", "0.28", "-0.21", "-0.49", "-0.66", "-1.29", "0.67", "-0.76", "0.23"]
sorting code:
datapct.sort(d3.descending);
arranges like:
["3.34", "3.09", "3.01", "2.67", "2.41", "1.91", "1.9", "1.58", "1.56", "1.5", "1.49", "1.14", "1.13", "1", "0.98", "0.85", "0.67", "0.67", "0.65", "0.53", "0.51", "0.51", "0.51", "0.49", "0.28", "0.23", "0.23", "0.18", "0.01", "0", "-2.88", "-2.09", "-1.67", "-1.58", "-1.37", "-1.29", "-0.88", "-0.87", "-0.86", "-0.76", "-0.75", "-0.67", "-0.66", "-0.64", "-0.63", "-0.53", "-0.49", "-0.42", "-0.42", "-0.41", "-0.38", "-0.35", "-0.27", "-0.22", "-0.21", "-0.14", "-0.07"]
image:
you're trying sort strings , that's why you're getting unexpected results. can see have array of strings they're in quotes.
to fix need convert string number can snippet:
datapct.foreach(function (d,i) { datapct[i] = +d; });
there discussion converting strings number in api documentation such here.
Comments
Post a Comment