admin管理员组文章数量:1183193
I am trying to understand how exactly sort() works and how I am supposed to use it.
I did some research (google) and went through the similar questions here on stackoverflow, but there are still a few things not 100% clear to me.
So my understanding so far is the following:
There are:
sort() without parameters: sorts only simple arrays of String values alphabetically and in ascending order
E.g.
// sort alphabetically and ascending:
var myArr=["Bob", "Bully", "Amy"]
myArr.sort() // Array now becomes ["Amy", "Bob", "Bully"]
sort() with a function as a parameter: sorts objects in arrays according to their properties; the items are, however, compared as numbers
myArr.sort(function(a,b) {
return a - b;
});
sort() with a function as a parameter: sorts objects in arrays according to their properties; the items can be numbers or Strings
myArr.sort(function(a, b) {
if (a.sortnumber < b.sortnumber) return -1;
else if (a.sortnumber > b.sortnumber) return 1;
return 0;
});
I tried sorting the following array with all these 3 sort() functions.
var myArr = [{
"sortnumber": 9,
"name": "Bob"
},
{
"sortnumber": 5,
"name": "Alice"
},
{
"sortnumber": 4,
"name": "John"
},
{
"sortnumber": 3,
"name": "James"
},
{
"sortnumber": 7,
"name": "Peter"
},
{
"sortnumber": 6,
"name": "Doug"
},
{
"sortnumber": 2,
"name": "Stacey"
}];
//myArr.sort(); // doesn't do anything since it doesn't know on what property to sort
/*
myArr.sort(function(a, b) {
return (a.sortnumber - b.sortnumber); // sorts array
return (a.name - b.name); // doesn't sort array
});
*/
/*
// sorts array even when I use name as property to sort on
myArr.sort(function(a, b) {
if (a.sortnumber < b.sortnumber) return -1;
else if (a.sortnumber > b.sortnumber) return 1;
return 0;
});
*/
console.log(myArr);
I am trying to understand how exactly sort() works and how I am supposed to use it.
I did some research (google) and went through the similar questions here on stackoverflow, but there are still a few things not 100% clear to me.
So my understanding so far is the following:
There are:
sort() without parameters: sorts only simple arrays of String values alphabetically and in ascending order
E.g.
// sort alphabetically and ascending:
var myArr=["Bob", "Bully", "Amy"]
myArr.sort() // Array now becomes ["Amy", "Bob", "Bully"]
sort() with a function as a parameter: sorts objects in arrays according to their properties; the items are, however, compared as numbers
myArr.sort(function(a,b) {
return a - b;
});
sort() with a function as a parameter: sorts objects in arrays according to their properties; the items can be numbers or Strings
myArr.sort(function(a, b) {
if (a.sortnumber < b.sortnumber) return -1;
else if (a.sortnumber > b.sortnumber) return 1;
return 0;
});
I tried sorting the following array with all these 3 sort() functions.
var myArr = [{
"sortnumber": 9,
"name": "Bob"
},
{
"sortnumber": 5,
"name": "Alice"
},
{
"sortnumber": 4,
"name": "John"
},
{
"sortnumber": 3,
"name": "James"
},
{
"sortnumber": 7,
"name": "Peter"
},
{
"sortnumber": 6,
"name": "Doug"
},
{
"sortnumber": 2,
"name": "Stacey"
}];
//myArr.sort(); // doesn't do anything since it doesn't know on what property to sort
/*
myArr.sort(function(a, b) {
return (a.sortnumber - b.sortnumber); // sorts array
return (a.name - b.name); // doesn't sort array
});
*/
/*
// sorts array even when I use name as property to sort on
myArr.sort(function(a, b) {
if (a.sortnumber < b.sortnumber) return -1;
else if (a.sortnumber > b.sortnumber) return 1;
return 0;
});
*/
console.log(myArr);
Here is also a fiddle.
So, my questions are:
- Is my understanding correct?
- Is there anything that I am missing?
- If the third case works at all times, can I always stick to it or are the other two cases more efficient in some way or have any advantages to the third case?
I would really appreciate it if anyone could elaborate on the above. Thank you.
Share Improve this question asked Aug 29, 2016 at 9:19 SetilySetily 8221 gold badge9 silver badges21 bronze badges 3- Use first or third approach, if you need to support old IE browsers. – Maris Commented Aug 29, 2016 at 9:29
- Is there anything that I am missing? Such questions are off-topic. Here we only deal with specific problems. – hindmost Commented Aug 29, 2016 at 9:30
- 1 @hindmost: Is there anything specific that I am missing to the specified topic, is how the question is meant to be read. – Setily Commented Aug 29, 2016 at 9:32
6 Answers
Reset to default 12Ok, so after some additional research, going through the MDN documentation, and the arraysort and arraysort2 links, which I found very helpful, I created a slide that could probably be of use to someone else, so I am posting it here. Thank you all for your answers!
First of all, you did a good research and covered almost all possible cases, and you can find the MDN documentation here
You just missed the case of Sorting non-ASCII characters
For sorting strings with non-ASCII characters, i.e. strings with accented characters (e, é, è, a, ä, etc.), strings from languages other than English: use String.localeCompare. This function can compare those characters so they appear in the right order.
var items = ['réservé', 'premier', 'cliché', 'communiqué', 'café', 'adieu'];
items.sort(function (a, b) {
return a.localeCompare(b);
});
// items is ['adieu', 'café', 'cliché', 'communiqué', 'premier', 'réservé']
According to Array reference (http://www.w3schools.com/jsref/jsref_sort.asp):
By default, the sort() method sorts the values as strings in alphabetical and ascending order.
So your first understanding about sort()
is correct. However, the second and third are not yet correct. First of all, they are both the same case, which is providing a sorting function to the sort()
method. This method should compare the a
and b
, and return negative, zero, or positive values, indicating if a
is less than, equals, or greater than b
. So for example, you can still compare your myArr
using the name
property like this:
myArr.sort(function(a,b) {
return a.name.localeCompare(b.name);
});
I found this at https://www.w3schools.com/js/js_array_sort.asp in "The Compare Function" section. Hope this helps, thank you :)
The Compare Function: The purpose of the compare function is to define an alternative sort order.
The compare function should return a negative, zero, or positive value, depending on the arguments:
function(a, b){return a - b}
When the sort() function compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.
If the result is negative a is sorted before b.
If the result is positive b is sorted before a.
If the result is 0 no changes are done with the sort order of the two values.
Example:
The compare function compares all the values in the array, two values at a time (a, b).
When comparing 40 and 100, the sort() method calls the compare function(40, 100).
The function calculates 40 - 100 (a - b), and since the result is negative (-60), the sort function will sort 40 as a value lower than 100.
You can use this code snippet to experiment with numerically and alphabetically sorting:
<html>
<body>
<h2>JavaScript Array Sort</h2>
<p>Click the buttons to sort the array alphabetically or numerically.</p>
<button onclick="myFunction1()">Sort Alphabetically</button>
<button onclick="myFunction2()">Sort Numerically</button>
<p id="demo"></p>
<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;
function myFunction1() {
points.sort();
document.getElementById("demo").innerHTML = points;
}
function myFunction2() {
points.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = points;
}
</script>
</body>
</html>
I think, you would like to combine the sort criteria, like this example which sort by name forst and then by number. Please watch 'John'
.
var myArr = [{ "sortnumber": 9, "name": "Bob" }, { "sortnumber": 5, "name": "Alice" }, { "sortnumber": 4, "name": "John" }, { "sortnumber": 3, "name": "James" }, { "sortnumber": 7, "name": "Peter" }, { "sortnumber": 6, "name": "Doug" }, { "sortnumber": 2, "name": "Stacey" }, { "sortnumber": 14, "name": "John" }, { "sortnumber": 12, "name": "John" }];
myArr.sort(function (a, b) {
return a.name.localeCompare(b.name) || a.sortnumber - b.sortnumber;
});
console.log(myArr);
I am validating something with an array in the browser console and suddenly run array.sort() function. Then I got the issue. array.sort() is not working properly for all data types in javascript/typescript. Ya, it's a mystery, I did not validate it during studying time. Ha, it's too fun, but it's interesting.
If we check the "developer.mozilla", they clearly mention it at top. But we didn't point out, how it works.
Array.prototype.sort()
The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted.
The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
I also got some interesting facts and decided to share them here:
-- It is a great learning for me
本文标签:
版权声明:本文标题:javascript - Difference between sort(), sort(function(a,b){return a-b;}); and sort(function(a,b){...}) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738310443a2074030.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论