The JavaScript array sort()function performs Lexicographic sorting. It is sorted based on the "string" value of each element. In this case, it 1is before 10, because although they have the same prefix, in 1short. They are both up 2, because 1up 2(i.e., He does not even look at the second symbol 10).
You can also write your own comparator function for sorting using whatever criteria you want. To sort numerically, try the following:
var values = [10, 2, 1];
console.log(values.sort(function(a,b) {return a-b}));
. .
, , :
var people = [
{
name: "Bob",
age: 42
},
{
name: "Alan",
age: 50
},
{
name: "Charlie",
age: "18"
}
];
console.log(JSON.stringify(people));
people.sort(function(a,b) {
if (a.name < b.name) return -1;
else if (a.name > b.name) return 1;
else return 0;
});
console.log(JSON.stringify(people));
people.sort(function(a,b) {
return a.age - b.age;
});
console.log(JSON.stringify(people));