Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform sort in js?

I have an array like this

var temp = [{"rank":3,"name":"Xan"},{"rank":1,"name":"Man"},{"rank":2,"name":"Han"}]

I am trying to sort it as follows

 temp.sort(function(a){ a.rank})

But its n ot working.Can anyone suggest help.Thanks.

like image 331
Daniel Avatar asked Mar 08 '17 12:03

Daniel


People also ask

How do you do sorting using JavaScript?

We can do this in JavaScript by using the sort() method directly or with the compare function. In case you are in a rush, here are the two ways: // order an array of names names. sort(); // order an array of objects with name users.

What is sort () in JavaScript?

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.

Does JS have a sort function?

In JavaScript, we can sort the elements of an array easily with a built-in method called the sort( ) function. However, data types (string, number, and so on) can differ from one array to another.

How do you sort numbers in JavaScript?

sort() method is used to sort the array elements in-place and returns the sorted array. This function sorts the elements in string format. It will work good for string array but not for numbers. For example: if numbers are sorted as string, than “75” is bigger than “200”.


2 Answers

With Array#sort, you need to check the second item as well, for a symetrical value and return a value.

var temp = [{ rank: 3, name: "Xan" }, { rank: 1, name: "Man" }, { rank: 2, name: "Han" }];

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

console.log(temp);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 125
Nina Scholz Avatar answered Sep 23 '22 00:09

Nina Scholz


You must compare them inside the sort function. If the function returns a negative value, a goes before b (in ascending order), if it's positive, b goes before a. If the return value is 0, they are equal:

temp.sort(function(a, b) {
    if (a.rank < b.rank) {
        return -1;
    } else if (a.rank > b.rank) {
        return 1;
    } else {
        return 0;
    }
});

You can use a shortcut method that subtracts the numbers to get the same result:

temp.sort((a, b) {
    return a.rank - b.rank;
});

For descending order:

temp.sort((a, b) {
    return b.rank - a.rank;
});

ES6 shortcut:

temp.sort((a, b) => b.rank - a.rank;
like image 30
Gorka Hernandez Avatar answered Sep 24 '22 00:09

Gorka Hernandez