Javascript: multi value sort

By : Jodes
Source: Stackoverflow.com
Question!

I have a problem that would be ideally handled by a RDBMS but I need it in Javascript. I was going to use Google gears but I have since discovered it's no longer in development.

What are some methods I could achieve the following?

I have a lot of products as JSON objects. Each has 3 properties I want to sort by, and I would want to be able to change the which property is sorted before the others. In SQL I might have written order by weight, height, power or other combinations.

The more powerful the solution the better, as I will probably want to expand requirements, all of which would be more easily handled by RDBMS, however I only want to know client-side options, as I will fall back to using a server-side RDBMS if absolutely necessary.

Thanks

Edit: Come to think of it, it might actually be quite simple just to use Array.sort(sortFn)?...

By : Jodes


Answers

Javascript Multi-Criteria / Multi-Parameter Sort

The easiest way to perform a javascript multi-criteria sort is to concatenate the criteria and compare them as 2 strings.

function sortByCriteria(data, criteria) {
    return data.sort(function (a, b) {

        var i, iLen, aChain, bChain;

        i = 0;
        iLen = criteria.length;
        for (i; i < iLen; i++) {        
            aChain += a[criteria[i]];
            bChain += b[criteria[i]];
        }

        return aChain.localeCompare(bChain);
    });
}

http://jsfiddle.net/oahxg4u3/6/



Thanks Adam, and everyone, I will remember those for when my requirements evolve. Anyway, here's the solution I came up with...

function compare(a, b){
    var weight =    a.weight - b.weight;
    var power  =    a.power  - b.power;
    var height =    a.height - b.height;

    if (weight)  return weight;
    if (power)    return power;
    if (height)   return height;
    return 0;
};
objArr.sort(compare);

Thanks again

By : Jodes


This video can help you solving your question :)
By: admin