The problem you have is that you push references to the date1 object. When you change the date on it in your loop, you update the object, but all references still point to the same object.

You need to either push a text representation of your date, or a copy of your date1 object

for (var i=0; date1 <= date2; date1.setDate(date1.getDate() + 1), i++) {
    alldates.push(new Date(date1));
    }

alert(alldates.join('\n'));

As suggested, with a while loop

while( date1 <= date2 ) {
  alldates.push(new Date(date1));
  date1.setDate( date1.getDate() +1 );
} 
Answer from jaudette on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Date
Date - JavaScript | MDN
The following examples show how to determine the elapsed time between two JavaScript dates in milliseconds. Due to the differing lengths of days (due to daylight saving changeover), months, and years, expressing elapsed time in units greater than hours, minutes, and seconds requires addressing a number of issues, and should be thoroughly researched before being attempted. ... // Using Date objects const start = Date.now(); // The event to time goes here: doSomethingForALongTime(); const end = Date.now(); const elapsed = end - start; // elapsed time in milliseconds
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Date › Date
Date() constructor - JavaScript | MDN
Given at least a year and month, this form of Date() returns a Date object whose component values (year, month, day, hour, minute, second, and millisecond) all come from the following parameters. Any missing fields are given the lowest possible value (1 for day and 0 for every other component).
🌐
W3Schools
w3schools.com › js › js_dates.asp
JavaScript Dates
Object Study Path Object Intro Object Properties Object Methods Object this Object Display Object Constructors JS Scope · JS Scope JS Code Blocks JS Hoisting JS Strict Mode JS Dates · JS Dates JS Date Formats JS Date Get JS Date Set JS Date Methods JS Temporal New · Temporal Study Path Temporal Intro Temporal vs Date Temporal Duration Temporal Now Temporal Instant Temporal PlainDate Temporal PlainTime Temporal PlainDateTime Temporal ZonedDateTime Temporal Arithmetic Temporal Migrate Temporal Reference JS Arrays
🌐
W3Schools
w3schools.com › js › js_date_methods.asp
JavaScript Date Methods
JSON Intro JSON Syntax JSON vs ... Prep JS Bootcamp JS Certificate JS Reference ... In JavaScript, date objects are created with new Date()....
🌐
TutorialsPoint
tutorialspoint.com › how-to-store-all-dates-in-an-array-present-in-between-given-two-dates-in-javascript
How to store all dates in an array present in between given two dates in JavaScript?
</h2> <div id = "output"></div> <script> var output = document.getElementById('output'); var date1 = new Date("2023-01-01"); var date2 = new Date("2023-01-11"); output.innerHTML += "The date1 is " + date1 + "<br/>"; output.innerHTML += "The date2 is " + date2 + "<br/>"; var dateArray = []; while (date1 <= date2) { dateArray.push(new Date(date1)); date1.setDate(date1.getDate() + 1); } output.innerHTML += "The date array is <br/>"; for (let i = 0; i < dateArray.length; i++) { output.innerHTML += dateArray[i] + " <br/>"; } </script> </body> </html>
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-store-all-dates-in-an-array-present-in-between-given-two-dates-in-javascript
How to store all dates in an array present in between given two dates in JavaScript ? - GeeksforGeeks
July 3, 2024 - The function getAllDates uses a for loop to iterate through dates between startDate and endDate, incrementing by one day each iteration. Dates are then concatenated into an array.
🌐
W3Resource
w3resource.com › javascript-exercises › javascript-date-exercise-11.php
JavaScript: Maximum date from an array of dates - w3resource
The code defines a JavaScript function named "max_date()" with one parameter 'all_dates', representing an array of date strings. ... It initializes two variables: 'max_dt' to store the maximum date string found so far and 'max_dtObj' to store ...
🌐
W3Schools
w3schools.com › jsref › jsref_obj_date.asp
JavaScript Date Reference
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST ... Array[ ] Array( ) at() concat() constructor copyWithin() entries() every() fill() filter() find() findIndex() findLast() findLastIndex() flat() flatMap() forEach() from() includes() indexOf() isArray() join() keys() lastIndexOf() length map() of() pop() prototype push() reduce() reduceRight() rest (...) reverse() shift() slice() some() sort() splice() spread (...) toReversed() toSorted() toSpliced() toString() unshift() values() valueOf() with() JS Boolean
🌐
W3Schools
w3schools.com › js › js_arrays.asp
JavaScript Arrays
Object Study Path Object Intro ... Display Object Constructors JS Scope · JS Scope JS Code Blocks JS Hoisting JS Strict Mode JS Dates · JS Dates JS Date Formats JS Date Get JS Date Set JS Date Methods JS Temporal New · Temporal Study Path Temporal Intro Temporal vs Date Temporal Now Temporal Instant Temporal PlainDate Temporal PlainTime Temporal PlainDateTime Temporal ZonedDateTime Temporal Duration Temporal Arithmetic Temporal Migrate Temporal Reference JS Arrays...
🌐
W3Resource
w3resource.com › javascript › object-property-method › date.php
Javascript Date Objects - Properties and Methods - w3resource
new Date(year, month, day, hours, minutes, seconds, milliseconds). [for example inauguration_day = new Date(97,8,15,10,05,0) ]. ... JavaScript Core objects, methods, properties. Previous: JavaScript valueOf() Method: Array Object Next: JavaScript constructor Property: Date Object
🌐
Mastering JS
masteringjs.io › tutorials › fundamentals › sort-by-date
How to Sort an Array by Date in JavaScript - Mastering JS
const d1 = new Date('2019-06-01'); const d2 = new Date('2018-06-01'); const d3 = new Date('2019-06-01'); const objects = [ { createdAt: d1, name: 'Test 1' }, { createdAt: d2, name: 'Test 2' }, { createdAt: d3, name: 'Test 3' } ]; objects.sort((a, b) => a.createdAt - b.createdAt); // [ 'Test 2', 'Test 1', 'Test 3' ] console.log(objects.map(o => o.name)); You could also sort without using the time portion of the date.
🌐
DEV Community
dev.to › askyt › sorting-an-array-of-objects-by-date-in-javascript-3pnb
Sorting an Array of Objects by Date in JavaScript - DEV Community
January 7, 2025 - const data = [ { name: 'Event 1', date: new Date('2023-01-15') }, { name: 'Event 2', date: new Date('2022-12-20') }, { name: 'Event 3', date: new Date('2023-03-05') } ]; data.sort((a, b) => a.date.getTime() - b.date.getTime()); console.log(data);
🌐
Medium
fireflysemantics.medium.com › searching-an-array-of-dates-with-javascript-aa8e8708708d
Searching an Array of Dates with Javascript - Ole Ersoy - Medium
October 26, 2020 - Searching an Array of Dates with Javascript Scenario We have a text input="11/25/2014" . We want to see whether the input matches any of the dates in the array: const dates = [new Date(2014, 11, 25) …
🌐
Reddit
reddit.com › r/learnjavascript › how to get minimum date from array of object
r/learnjavascript on Reddit: How to get minimum date from array of object
October 25, 2021 -

Hello,

I would like to get the minimum date of this array of objects bellow:

let activities = [
  { title: 'Hiking', date: '2019-06-13' },
  { title: 'Shopping', date: '2019-06-10' },
  { title: 'Trekking', date: '2019-06-22' },
  { title: 'Trekking', date: null }
]

let sortedActivities = activities.sort((a, b) => new Date(a.date) - new Date(b.date))
console.log(sortedActivities[0])

The problem is when date activities.date is null it always returns null .

What's the best way to reject null value from this comparison ?

Thanks

Top answer
1 of 16
2235

Simplest Answer

array.sort(function(a,b){
  // Turn your strings into dates, and then subtract them
  // to get a value that is either negative, positive, or zero.
  return new Date(b.date) - new Date(a.date);
});

More 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;
});

Or more tersely:

array.sort(function(o1,o2){
  return sort_o1_before_o2 ? -1 : sort_o1_after_o2 ? 1 : 0;
});

Generic, Powerful Answer

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

Use it like so:

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

If your date is not directly comparable, make a comparable date out of it, e.g.

array.sortBy(function(o){ return new Date( o.date ) });

You can also use this to sort by multiple criteria if you return an array of values:

// Sort by date, then score (reversed), then name
array.sortBy(function(o){ return [ o.date, -o.score, o.name ] };

See http://phrogz.net/JS/Array.prototype.sortBy.js for more details.

2 of 16
387

@Phrogz answers are both great, but here is a great, more concise answer:

array.sort(function(a,b) { return a.getTime() - b.getTime() });

Using the arrow function way

array.sort((a,b) => a.getTime() - b.getTime());

found here: Sort date in Javascript