-2

For example I have this array:

array = [
  {id : 0, name : "alex"},
  {id : 2, name : "mark"},
  {id : 1, name : "sarah"}
]

I want to sort this array to be in order depending on the id value.

Kunok
  • 8,089
  • 8
  • 48
  • 89
  • Can you show us what have you tried? – Rajesh Feb 07 '16 at 04:50
  • 2
    Possible duplicate of [Sort array of objects by string property value in JavaScript](http://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value-in-javascript) – Rajesh Feb 07 '16 at 04:52
  • I already checked this post and it is not same. – Kunok Feb 07 '16 at 04:52
  • You are looking to sort array of objects based on a property in that object. Right? – Rajesh Feb 07 '16 at 04:54
  • The answers on this question are more legit for this specific problem than answers on the one you linked even if the question is very similar. In any other case it is duplicate indeed. – Kunok Feb 07 '16 at 04:56

2 Answers2

2

You can use sort function to sort the array.

Note: Your array is incorrect,it need be {id : 0, name : "alex"}.It should be colon(:) but not equal(=)

array = [
          {id : 0, name : "alex"},
          {id : 2, name : "mark"},
          {id : 1, name : "sarah"}
        ]
        var sortedArray =array.sort(function(a,b){
        return a.id-b.id; // for ascending order

        });
        console.log(sortedArray)

JSFIDDLE

Documentation: sort.`

Kunok
  • 8,089
  • 8
  • 48
  • 89
brk
  • 48,835
  • 10
  • 56
  • 78
  • Yeah sorry I wasn't careful when I was writing a question, I fixed it now. Can you provide documentation link for `sort` method so people can check browser support and other information when they are searching for a solution for their problem? – Kunok Feb 07 '16 at 05:03
1

Something like that?, you can use .sort() function

var array = [
  {id : 0, name : "alex"},
  {id : 2, name : "mark"},
  {id : 1, name : "sarah"}
]

var sortedArray = array.sort(function(obj, obj2){
  return obj.id - obj2.id
});

document.write("<pre>" + JSON.stringify(sortedArray,1,1) + "</pre>");