Reputation:
I want sort a Array in JavaScript by value of object which is that array holding.
For example:
Input
arr = [{id:[2, 'second']},{id:[8, 'eighth']},{id:[1, 'first']}];
My excepted output is:
sorted_arr = [{id:[8, 'eighth']},{id:[1, 'first']},{id:[2, 'second']}];
Note: Please give sort by alphabet
Upvotes: 2
Views: 76
Reputation: 631
You can make a compare function like this which will do as require.
arr.sort(function(a, b){
return a["id"][0]-b["id"][0];
});
Suppose in case when both id's are equal, in that case if you want to do sorting on basis of your second parameter i.e first,second third then the code will be
arr.sort(function(a, b){
if(a["id"][0]===b["id"][0])
{
if(a["id"][1] < b["id"][1]) return -1;
if(a["id"][1] > b["id"][1]) return 1;
return 0;
}
return a["id"][0]-b["id"][0];
});
Upvotes: 2
Reputation: 115222
You can use sort()
arr = [{
id: [2, 'second']
}, {
id: [4, 'fourth']
}, {
id: [1, 'first']
}];
var sort = arr.sort(function(a, b) {
return a.id[0] - b.id[0];
});
document.write('<pre>' + JSON.stringify(sort, null, 3) + '</pre>');
If you want to sort based on the word in array then you need to compare the values
arr = [{
id: [2, 'second']
}, {
id: [4, 'fourth']
}, {
id: [1, 'first']
}];
var sort = arr.sort(function(a, b) {
if (a.id[1] > b.id[1]) return 1;
if (a.id[1] < b.id[1]) return -1;
return 0;
});
document.write('<pre>' + JSON.stringify(sort, null, 3) + '</pre>');
Upvotes: 1