javascript - What is the logic behind the sort method used with a compareFunction? -
i trying sort() method comaprefunction , not understand how comparenumbers() works. used 2 variables returns -3, when used on array sort method returns sorted array. why work this?
var things = ['elvis',555,'r2d2']; function comparenumbers(a, b){ homecoming a-b; } var = 5; var b = 8; console.log(comparenumbers(a,b)); //returns -3 console.log(comparenumbers(things));//returns nan console.log(things.sort(comparenumbers(a,b)));//returns sorted array
what logic behind sort method used comparefunction returns sorted array? why doesn't homecoming nan?
where can check code behind method library or documentation?
i saw understanding sort() comparefunction overwhelming me @ stage.
you're calling comparenumbers
, passing homecoming value sort
, isn't want. want pass function sort
, sort
calls it:
console.log(things.sort(comparenumbers)); // no (), no , b -----------------^
but it's of import note when either a
or b
"elvis"
or "r2d2"
, comparator function (comparenumbers
) returns nan
, meaning it's not "consistent comparing function" according the specification. means whatever sort
@ point "implementation defined" — totally javascript engine's authors, not covered specification @ all, , vary 1 engine another. sort
expects see negative number, 0
, or positive number, not nan
. things
array shouldn't sorted numerically @ all, 2 of entries not numbers nor can correctly converted numbers.
here's illustration of using comparator function correctly: in case, takes array , sorts them according length of each entry converted string:
class="snippet-code-js lang-js prettyprint-override">var things = ['elvis',555,'r2d2']; function comparelengths(a, b){ homecoming string(a).length - string(b).length; } snippet.log(things.sort(comparelengths));
class="snippet-code-html lang-html prettyprint-override"><!-- temporary snippet object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
javascript sorting
No comments:
Post a Comment