mikesta707 Posted August 5, 2009 Share Posted August 5, 2009 Ok, I have a 2-d array, and I am trying to sort it numerically by the 6th column (or array[5]). The array is something like array = ("Stuff", "Something else" "other stuff", 95, 95, 100); The 6th column is the percent of quotient of the 4th and 5th column times 100 (basically a percent) So the sorting code I have looks like the following function value_sort(a,b) { a = a[5]; b = b[5]; return a == b ? 0 : (a > b ? -1 : 1) } full_array.sort(value_sort) It does sort it somewhat, but When it sorts, anything below 100% (IE 99 % 98% etc.) is sorted correctly, but 100% values are below everything but 0% values. so if the array's 6th column looks like the following 100 99 98 97 96 100 100 100 5 6 7 8 0 0 0 then the sorted array will look like: 99 98 97 96 8 7 6 5 100 100 100 100 0 0 0 I don't really understand why. Anyone got any ideas? Quote Link to comment https://forums.phpfreaks.com/topic/168952-solved-custom-javascript-array-sort-not-sorting-correctly/ Share on other sites More sharing options...
mikesta707 Posted August 5, 2009 Author Share Posted August 5, 2009 never mind, I figured it out. For those who are curious the reason goes as follows: Using my method, it is sorting as a numeric string, not as a quantifiable number, and since the value "100" starts with 1, it goes below every other number except for zero. To fix this, I added a preceding "0" to any number of two digits or lower. the fixed function looks like the following: function value_sort(a,b) { a = a[5]; b = b[5]; if (a.length < 3){ pre = "0"; a = pre + a; } if (b.length < 3){ pre = "0"; b = pre + b; } return a == b ? 0 : (a > b ? -1 : 1); } Quote Link to comment https://forums.phpfreaks.com/topic/168952-solved-custom-javascript-array-sort-not-sorting-correctly/#findComment-891426 Share on other sites More sharing options...
haku Posted August 5, 2009 Share Posted August 5, 2009 You can also cast your data as a number type in order to do this, which would remove the necessity for leading zeros. Quote Link to comment https://forums.phpfreaks.com/topic/168952-solved-custom-javascript-array-sort-not-sorting-correctly/#findComment-891439 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.