简体   繁体   中英

What's the difference between array.sort() and array.sort(function(a,b) { return a - b; })?

I have a piece of code which triggers some actions. Before that it simply sorts weights. Everything works well when I use: weight.sort() where weight is an non-empty array eg [10 20 30 40] , but when I change that to:

weight.sort(function(a,b) {
    return a - b;
});

one of the actions has no effect (display a div). Being honest I don't know what might cause the difference. It seems strange to me because weight is the same after sorting with both methods and clearly changing that piece of code makes my script working or not. There are no errors in FireBug.

If you do

weight = weight.sort

the items are sorted by using lexicographical comparison. => 2 > 10

But when you do

weight = weight.sort(function(a,b) { return a - b; });

the items are compared as numbers instead of string and list sorted in ascending order. => 2 < 10

Also,

weight = weight.sort(function(a,b){return b-a});

will sort by descending order.

We usually use such kind of sort to implement some kind of custom compare. In this case the only difference with just calling sort is the order of elements - using the code you show, the array will be sorted in descending order(from big to small values) instead of the typical increasing order.

Note that the no-argument sort would return ba instead of ab which differs in sign and thus reverses the comparison.

Array.prototype.sort without a custom sorting function sorts items in lexicographical order .

You can define a custom function to sort any type of items, using any of their properties. Just make sure the function returns a negative/positive number or 0 based on your comparison result. For example, to sort objects with name properties based on their names, you can use:

items.sort(function (a, b) {
    return a.name.localeCompare(b.name);
});

Or to sort the items by their priority properties (Number):

items.sort(function (a, b) {
    return a.priority - b.priority;
});

In your custom sorters, you can compare on as many properties as you like. Also make sure you handle undefined items or item properties gracefully. A fortified sort-by-name example:

items.sort(function (a, b) {
    var aName = a && a.name || "",
        bName = b && b.name || "";
    return aName.localeCompare(bName);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM