Basically, I'm trying to sort an array of objects by property.
Say I have three objects within an array, each with a property views
var objs = [
{
views: '17'
},
{
views: '6'
},
{
views: '2'
}
];
Using the sort method on the array objs
:
function sortByProperty(property) {
return function (a,b) {
/* Split over two lines for readability */
return (a[property] < b[property]) ? -1 :
(a[property] > b[property]) ? 1 : 0;
}
}
objs.sort(sortByProperty('views'));
I expect objs
to now be in the reverse order basically, however the '17'
seems to be treated as less than '6'
and '2'
. I realise this is probably because of the '1'
.
Any ideas on resolving this problem?
I realise I could iterate through each object and convert to integers - but is there a way to avoid doing that?
JSFiddle: http://jsfiddle.net/CY2uM/