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?
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?
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.
console.log to document.write and also added JSON.stringify() so as to make your snippet more useful :)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.