Sorting an Object Array by Date Property
To sort an array of objects by a date property, you can utilize JavaScript's sort() function in conjunction with a custom comparator. The process involves comparing the date values and returning a negative, positive, or zero value based on their order.
Simple Answer:
array.sort(function(a, b) { return new Date(b.date) - new Date(a.date); });
This comparator creates a date object for both dates and subtracts their values. A negative value indicates that a is closer to the current date than b, a positive value means b is closer, and zero indicates equality.
Generic Answer:
array.sort(function(o1, o2) { if (sort_o1_before_o2) return -1; else if (sort_o1_after_o2) return 1; else return 0; });
This more generic approach allows for a custom determination of the sorting order by defining separate conditions for sorting o1 before or after o2.
Powerful Answer:
A powerful solution is to define a custom non-enumerable sortBy function using a Schwartzian transform on all arrays:
(function() { if (typeof Object.defineProperty === 'function') { try { Object.defineProperty(Array.prototype, 'sortBy', { value: sb }); } catch (e) {} } if (!Array.prototype.sortBy) Array.prototype.sortBy = sb; function sb(f) { for (var i = this.length; i;) { var o = this[--i]; this[i] = [].concat(f.call(o, o, i), o); } this.sort(function(a, b) { for (var i = 0, len = a.length; i < len; ++i) { if (a[i] != b[i]) return a[i] < b[i] ? -1 : 1; } return 0; }); for (var i = this.length; i;) { this[--i] = this[i][this[i].length - 1]; } return this; } })();
This allows for concise and powerful sorting:
array.sortBy(function(o) { return o.date });
You can also expand this approach to handle multiple criteria in the sorting process by returning an array of values in the comparator function.
The above is the detailed content of How to Sort an Array of Objects by Date Property in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!