I want to sort the Array, according to the property such as this:
[
{num:5},{num:3},{num:6},{num:9}
]
After the sort, I want to get
[
{num:3},{num:5},{num:6},{num:9}
]
How to do it in JavaScript?
A sort function (literal) returns 1, -1, 0 for ascending, descending and equal respectively.
array.sort(function(a, b) {
return a.num - b.num
});
the_array.sort(function(a,b) { return a.num-b.num } );
其中sort()中的函数是比较器
var arr = [ {num:5},{num:3},{num:6},{num:9} ]; arr.sort(function(a,b) { return a.num-b.num; }); document.write(JSON.stringify(arr));
If you would need to sort items backwards it would be b.num-a.num
.
In this case, you should learn to use lambda expression witch is the key of functional programming. The answer is quite easy:
arr.sort(function(a,b){
return a.num - b.num;
})
If you don't know the high order function or lambda you are not actually writing JavaScript code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.