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?
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 } );
where the function inside the sort() is the comparator
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 :)
– nicael
Apr 1 '15 at 8:41
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.