0

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?

4
  • 2
    What did you try already? there are a tons of questions like this one anyway! :P Commented Apr 1, 2015 at 8:33
  • @briosheje I do not do kind of the sort before. I have no idea. :( Commented Apr 1, 2015 at 8:35
  • You can either use .sort, .filter or .map, your choice! :P Commented Apr 1, 2015 at 8:37
  • Do you have a JSON string with that content? Otherwise it's just an array of objects, and there is no JSON involved at all. Commented Apr 1, 2015 at 8:44

4 Answers 4

7

A sort function (literal) returns 1, -1, 0 for ascending, descending and equal respectively.

array.sort(function(a, b) {
      return a.num - b.num
});
Sign up to request clarification or add additional context in comments.

Comments

6

the_array.sort(function(a,b) { return a.num-b.num } );

where the function inside the sort() is the comparator

Comments

3

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.

1 Comment

I changed console.log to document.write and also added JSON.stringify() so as to make your snippet more useful :)
2

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.

4 Comments

@nicael Actually, there are no answers while I'm editing this post.
There are three answers which were posted before yours and the are completely identical. Yours is, believe me, excess.
I think the answers should be based on their correctness rather than whether they are identical to others.
@nicael In this question, you should not only focus on the answer, as you know it's quite simple but what a JavaScript programmer should know is the theory behind the answer, that's why I mention the two points in my answer and actually not excess.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.