Skip to content Skip to sidebar Skip to footer

Array Sort In JS

What's going on here? var values = [10, 2, 1]; console.log(values.sort()); output: [1, 10, 2] http://jsfiddle.net/A2vRt/

Solution 1:

JavaScript's array sort() function is doing Lexicographic sorting. It is sorting based on the "string" value of each element. In that case, 1 is before 10 because although they have the same prefix, 1 is shorter. They are both before 2 because 1 is before 2 (i.e. it never even looks at the second character of the 10).

You can also write your own "comparator" function to sort using whatever criteria you want. To sort numerically, try this:

var values = [10, 2, 1];
console.log(values.sort(function(a,b) {return a-b}));

For more details on Array sorting, see here.

And just for fun, a more complex example, sorting a complex object using different methods:

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));

Solution 2:

Default sort order is alphabetic and ascending.When numbers are sorted alphabetically, "40" comes before "5".To perform a numeric sort, you must pass a function as an argument when calling the sort method you need a function that defines the sort order. four your case use :

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

Solution 3:

Javascript sort works alphabetically. So you have to provide your own sort function. The function should return + for greater, 0 for equal and - for lesser value. So for ascending order try this:

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

Post a Comment for "Array Sort In JS"