javascript sort multi array/obj


SUBMITTED BY: Guest

DATE: Nov. 11, 2013, 11:50 a.m.

FORMAT: JavaScript

SIZE: 1.1 kB

HITS: 999

  1. function dynamicSort(property) {
  2. var sortOrder = 1;
  3. if(property[0] === "-") {
  4. sortOrder = -1;
  5. property = property.substr(1);
  6. }
  7. return function (a,b) {
  8. var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
  9. return result * sortOrder;
  10. }
  11. }
  12. function dynamicSortMultiple() {
  13. /*
  14. * save the arguments object as it will be overwritten
  15. * note that arguments object is an array-like object
  16. * consisting of the names of the properties to sort by
  17. */
  18. var props = arguments;
  19. return function (obj1, obj2) {
  20. var i = 0, result = 0, numberOfProperties = props.length;
  21. /* try getting a different result from 0 (equal)
  22. * as long as we have extra properties to compare
  23. */
  24. while(result === 0 && i < numberOfProperties) {
  25. result = dynamicSort(props[i])(obj1, obj2);
  26. i++;
  27. }
  28. return result;
  29. };
  30. }

comments powered by Disqus