3

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/

3 Answers 3

3

Javascript is somewhat typed language; the < means alphabetical sort for strings, numeric sort for numbers. The only way is to coerce the values into numbers. Unary operator + helps here. Thus try

function sortByNumericProperty(property) {
    return function (a,b) {
        var av = +a[property], bv = +b[property];
        /* Split over two lines for readability */
        return (av < bv) ? -1 : 
               (av > bv) ? 1 : 0;
    }
}

But generally the common idiom (also documented on MDN)

function sortByNumericProperty(property) {
    return function (a,b) {
        return a[property] - b[property];
    }
}

Should also work.

3
  • Performance wise, do you think it'd be better to do this vs iterating over the array and converting each property to an integer beforehand? Commented Aug 18, 2013 at 17:02
  • In this case implicit conversion is also happening. Commented Aug 18, 2013 at 17:04
  • 1
    ahren: it really should not matter too much; most of the time the difference should be neglible. Commented Aug 18, 2013 at 17:07
2

if a[property] and b[property] can be parsed to numbers

function sortByProperty(property) {
    return function (a,b) {
            return a[property] - b[property];
    }
}
0

You may have to convert your values to integer before using it -

function sortByProperty(property) {
    return function (a,b) {
        var x = parseInt(a[property]);  
        var y = parseInt(b[property])
        /* Split over two lines for readability */
        return (x < y) ? -1 : (x > y) ? 1 : 0;
    }
}
1
  • Yeah, I realise I could simply parseInt everything - but it's not quite what I was hoping for... Commented Aug 18, 2013 at 16:57

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.