How to useSpread Operator in Javascript

To select the minimum and maximum dates in an array, use the spread operator to clone the array, then apply `Math.min` and Math.max with the spreaded array, respectively.

Example: In this example, we are using sort() Method.

Javascript
let dates = [new Date('2022-01-01'), new Date('2022-03-15'), new Date('2022-02-10')];
let minDate = new Date(Math.min(...dates));
let maxDate = new Date(Math.max(...dates));
console.log(minDate);
console.log(maxDate);

Output
2022-01-01T00:00:00.000Z
2022-03-15T00:00:00.000Z

How to select Min/Max dates in an array using JavaScript ?

Given an array of JavaScript date. The task is to get the minimum and maximum date of the array using JavaScript. 

Below are the following approaches:

Table of Content

  • Using Math.max.apply() and Math.min.apply() Methods
  • Using reduce() method
  • Using Spread Operator
  • Using Array.prototype.sort with a custom comparator

Similar Reads

Approach 1: Using Math.max.apply() and Math.min.apply() Methods

Get the JavaScript dates in an array.Use Math.max.apply() and Math.min.apply() function to get the maximum and minimum dates respectively....

Approach 2: Using reduce() method

Get the JavaScript dates in an array.Use reduce() method in an array of dates and define the respective function for the maximum and minimum dates....

Approach 3: Using Spread Operator

To select the minimum and maximum dates in an array, use the spread operator to clone the array, then apply `Math.min` and Math.max with the spreaded array, respectively....

Approach 4: Using Array.prototype.sort with a custom comparator

Using Array.prototype.sort with a custom comparator function sorts an array of dates in ascending order. The first element (`dates[0]`) is the minimum date, and the last element (`dates[dates.length – 1]`) is the maximum date, efficiently determining the min/max dates in the array....