JS sort() for a list of floats
Hi, I'm writing a simple code for calculating ratio of fundamentals and its partials with JS object written in Javascript and found out weird thing.
so the list function's structure would be like this:
function list(){
myval = arrayfromargs(arguments)
var newList;
newList = myval.slice() //copy list
post("received list " + myval + "\n");
post("sorted list : " + newList.sort() + '\n')
if(myval.length > 0){
outlet(0, myval) //output array is same as just a variable.
outlet(1, myval.length)
post("list length: "+ myval.length+'\n')
}else{
outlet(1,0)
}
}
as I input a list of integers such as [1, 3, 2] it prints out [1,3,2] and [1, 2, 3] (the sorted one)
but if I send [2.3 14.88, 7.83], the result in max console is:
js: received list 2.299999952316284,14.880000114440918,7.829999923706055
js: sorted list : 14.880000114440918,2.299999952316284,7.829999923706055
then outputs a list [14.88 2.3 7.83] while [zl sort] gives me well sorted one [2.3 7.83 14.88]
I know the [zl sort] works very well in this situation though, I want to know why JS gives this consequences.
it looks like js sorts your array as strings instead of as numbers. Your first example works only because they are single digits, so it's redundant. Here's a stack overflow link to explain:
https://stackoverflow.com/questions/1063007/how-to-sort-an-array-of-integers-correctly