Array Sort in JS

What's going on here?

var values = [10, 2, 1];
console.log(values.sort());

exit:

[1, 10, 2]

http://jsfiddle.net/A2vRt/

0
source share
3 answers

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)); // Before sorting
people.sort(function(a,b) { // Sort by name
    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) { // Sort by age
    return a.age - b.age;
});
console.log(JSON.stringify(people));
+7

- . , "40" "5". , , . :

values.sort(function(a,b){return a-b})
+3

Javascript . . + , 0 - . :

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

All Articles