Home > Web Front-end > JS Tutorial > How to Sort an Array of Objects by Date Property in JavaScript?

How to Sort an Array of Objects by Date Property in JavaScript?

DDD
Release: 2024-12-21 08:01:09
Original
996 people have browsed it

How to Sort an Array of Objects by Date Property in JavaScript?

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);
});
Copy after login

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;
});
Copy after login

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;
  }
})();
Copy after login

This allows for concise and powerful sorting:

array.sortBy(function(o) { return o.date });
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template