0

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)?...

5
  • I'd look at downloading "datatables" for jquery Commented Jan 21, 2013 at 4:29
  • This post has similiar problem that the answers may help you: stackoverflow.com/questions/14245016/… Commented Jan 21, 2013 at 4:36
  • My first thought was nodejs. Commented Jan 21, 2013 at 4:36
  • What will you do with the sorted objects? Is this just for presentation? Are you just sorting a table based on a column? Commented Jan 21, 2013 at 4:36
  • No it wasn't for presentation Commented Jan 21, 2013 at 4:55

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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/

Comments

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.