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.
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.
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.
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.
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”.
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; }
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With