Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's another one that's perhaps closer to your idea for the syntax</p> <pre><code>function sortObjects(objArray, properties /*, primers*/) { var primers = arguments[2] || {}; // primers are optional properties = properties.map(function(prop) { if( !(prop instanceof Array) ) { prop = [prop, 'asc'] } if( prop[1].toLowerCase() == 'desc' ) { prop[1] = -1; } else { prop[1] = 1; } return prop; }); function valueCmp(x, y) { return x &gt; y ? 1 : x &lt; y ? -1 : 0; } function arrayCmp(a, b) { var arr1 = [], arr2 = []; properties.forEach(function(prop) { var aValue = a[prop[0]], bValue = b[prop[0]]; if( typeof primers[prop[0]] != 'undefined' ) { aValue = primers[prop[0]](aValue); bValue = primers[prop[0]](bValue); } arr1.push( prop[1] * valueCmp(aValue, bValue) ); arr2.push( prop[1] * valueCmp(bValue, aValue) ); }); return arr1 &lt; arr2 ? -1 : 1; } objArray.sort(function(a, b) { return arrayCmp(a, b); }); } // just for fun use this to reverse the city name when sorting function demoPrimer(str) { return str.split('').reverse().join(''); } // Example sortObjects(homes, ['city', ['price', 'desc']], {city: demoPrimer}); </code></pre> <p>Demo: <a href="http://jsfiddle.net/Nq4dk/2/" rel="noreferrer">http://jsfiddle.net/Nq4dk/2/</a></p> <hr> <p>Edit: Just for fun, <a href="http://jsfiddle.net/Nq4dk/3/" rel="noreferrer">here's a variation</a> that just takes an sql-like string, so you can do <code>sortObjects(homes, "city, price desc")</code></p> <pre><code>function sortObjects(objArray, properties /*, primers*/) { var primers = arguments[2] || {}; properties = properties.split(/\s*,\s*/).map(function(prop) { prop = prop.match(/^([^\s]+)(\s*desc)?/i); if( prop[2] &amp;&amp; prop[2].toLowerCase() === 'desc' ) { return [prop[1] , -1]; } else { return [prop[1] , 1]; } }); function valueCmp(x, y) { return x &gt; y ? 1 : x &lt; y ? -1 : 0; } function arrayCmp(a, b) { var arr1 = [], arr2 = []; properties.forEach(function(prop) { var aValue = a[prop[0]], bValue = b[prop[0]]; if( typeof primers[prop[0]] != 'undefined' ) { aValue = primers[prop[0]](aValue); bValue = primers[prop[0]](bValue); } arr1.push( prop[1] * valueCmp(aValue, bValue) ); arr2.push( prop[1] * valueCmp(bValue, aValue) ); }); return arr1 &lt; arr2 ? -1 : 1; } objArray.sort(function(a, b) { return arrayCmp(a, b); }); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload