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.
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.
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)
Documentation: sort.`
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>");