Is there a glitch in the console when sorting an array of dates?

I'm puzzled by the fact that the console is displaying a sorted array in both logs. It doesn't make sense to me because it should not be sorted at the first log, right?

  static reloadAndSortItems() {
    let array = [];
    const items = Store.getStoredItems();

    items.forEach(function (item) {

      // converting stored date back to date object

      let episodeDate = Date.parse(item.episode);
      let parsedEpisode = new Date(episodeDate);

      array.push(parsedEpisode);

    });

    **// array should not be sorted at this point
    console.log('not sorted', array);**

    let tested = array.sort(function (a, b) {
      return a - b
    });
    **// array should be sorted at this point
    console.log('sorted', tested);**

  }

The incoming array is out of order:

["2018-09-13T00:30:00.000Z","2018-09-14T05:25:00.000Z","2018-09-13T00:30:00.000Z","2018-09-11T01:30:00.000Z","2018-09-11T01:30:00.000Z"]

Answer №1

One reason for this is that the sort() method both modifies the original array and returns a new one, resulting in two arrays with identical element orders:

let arr = [1, 6, 2, 9, 3, 7];
let result = arr.sort((a, b) => a - b);

console.log('Original:', arr);
console.log('Final:', result);

To prevent this behavior, you can create an additional array (using, for example, the map() method, which creates a new array without modifying the original), and then use it as your initial array:

let arr = [1, 6, 2, 9, 3, 7];
let duplicate = arr.map(d => d);
arr.sort((a, b) => a - b);

console.log('Sorted:', arr);
console.log('Duplicate of the initial array:', duplicate);

Answer №2

When using the sort() method, it's important to note that it mutates the array that it is called on. Therefore, it is recommended to log the array variable rather than the tested variable:

static reloadAndSortItems() {
    let array = [];
    const items = Store.getStoredItems();

    items.forEach(function (item) {

      // Convert stored date back to a Date object

      let episodeDate = Date.parse(item.episode);
      let parsedEpisode = new Date(episodeDate);    

      array.push(parsedEpisode);    
    });

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

    console.log('sorted', array);    
  }

Alternatively, you can clone the array variable by using .map(), and then apply the .sort() method on the cloned array like this:

static reloadAndSortItems() {
    let array = [];
    const items = Store.getStoredItems();

    items.forEach(function (item) {

      // Convert stored date back to a Date object

      let episodeDate = Date.parse(item.episode);
      let parsedEpisode = new Date(episodeDate);    

      array.push(parsedEpisode);    
    });

    // Copy/clone the array using map into tested variable
    const tested = array.map(function(item) { return item; });

    // Sort the tested array. Calling sort on tested will leave array unaffected
    tested.sort(function (a, b) {
      return a - b
    });

    console.log('sorted', tested);  // Sorted
    console.log('array', array);    // Unsorted
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display validation in HTML5 only when the form is submitted

Here is the code snippet I am referring to: <input required pattern="[0-9]{5,10}" oninput="setCustomValidity('')" oninvalid="setCustomValidity('Type something')" /> I'm looking for a way to remove o ...

Unable to automatically prompt the button inside the iframe

In this scenario, an Iframe is automatically generated by a JavaScript script. I am looking to simulate a click by triggering a button, but unfortunately, it is not working as expected. You can view the code on JSFiddle. I have attempted various approache ...

I'm attempting to utilize a basic webcam capture upload feature, but it seems that the upload function is not functioning properly

UPDATE: This is the complete code that I simply copied and pasted. <!DOCTYPE HTML> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script language="JavaScript" type="text/javascrip ...

What is the best way to determine the dimensions of a KonvaJs Stage in order to correctly pass them as the height/width parameters for the toImage function

Currently, I am using KonvaJs version 3.2.4 to work with the toImage function of the Stage Class. It seems that by default, toImage() only captures an image of the visible stage area. This is why there is a need to provide starting coordinates, height, and ...

Tips on displaying a selected choice | Utilizing Material UI Autocomplete

I have successfully fetched data from an API and used it as options in Material UI Autocomplete. However, when I select an option and send it back to the API using a POST request, the selected category is displayed as a number (0) instead of text, as shown ...

Generate an automatic "proxy" for ASP.NET MVC Controller to communicate with AngularJs service

Whenever I utilize an ASP.NET MVC controller with AngularJS, the majority of my controller functions consist of JSON results. When creating my AngularJS service, I find myself repeatedly writing similar code to handle GET or POST calls to my ASP.NET contro ...

Express.io is encountering an issue where it is unable to read the property 'expires' of an undefined element

I am new to working with node.js and I am attempting to utilize express.io for saving cookies. Following a tutorial at https://github.com/techpines/express.io/tree/master/examples#sessions, I have encountered the following error: root@server1 [/nodeexamp ...

Encountering difficulty retrieving the value of a hidden input with jQuery's find method

When a user clicks on the delete icon, I want to retrieve the value of the hidden input inside the "delete" class. However, I am getting an undefined result. Can someone please guide me on where I might be going wrong? <table class="items-list"> ...

Show a distinct row from an API using React

I am attempting to create a map function to display all the items from the API Screenshot of code showing the items Here is the console log displaying the fetched items from the API I encountered an error with the map function not working. Any solutions ...

Guide on utilizing Json.net for extracting an array from a json document

After conducting thorough research, I have come across several solutions to similar problems like mine. Unfortunately, none of them have proven to be successful so far. My main goal is to parse a json file where the first item is an array structured like t ...

The anchor tag fails to trigger the onClick function in React

I'm having trouble updating the component state in my React app when clicking on an anchor tag within the render method. I've attempted to bind the function in the constructor, but the console.log statement is still not being called. Here's ...

JavaScript is failing to execute the DELETE SQL transaction

I've been attempting to clear out my html5 local sql database, but for some reason, it's not working as expected. Below is the code I'm using, and no matter what I try, the alert always shows that the length is greater than 0. Any ideas why ...

The Material UI Popover is appearing outside the designated boundaries

In my app, I am using the code below to implement a react-dates picker controller inside a popover element. The functionality works well in most scenarios, but there is an issue when the button triggering the popover is located at the bottom of the screen, ...

Unable to locate module with React and Material-UI integration

When attempting to implement a Material button in my React app, I encountered the following error: Failed to compile. ./node_modules/@material-ui/core/styles/index.js Module not found: Can't resolve '/Users/hugovillalobos/Documents/Code/Lumiere ...

Error: Cannot iterate over Redux props map as it is not a function

I've encountered an issue while trying to render out a Redux state by mapping through an array of objects. Despite receiving the props successfully, I keep getting an error stating that 'map is not a function'. It seems like the mapping func ...

Setting all array elements to zero in C# without employing for loops

In C#, there is a shortcut to initialize an array called Buffer with all elements set to 0 without using a for loop. You can simply use the following one-liner: byte[] Buffer = Enumerable.Repeat((byte)0, 50).ToArray(); ...

Creating a private variable to perform a select_sum query

I have defined private variables in my CodeIgniter code like this: private $table = 'phone'; private $column_order = array(null, 'name', 'price'); private $type = array('type'); private $battery_consumption = array ...

Encountering issues with creating a session in Selenium/webdriver while utilizing Safari 12

Ever since making the update to Safari 12, my automated scripts have been encountering a new error: SessionNotCreatedError: Request body does not contain required parameter 'capabilities'. (Interestingly, this error is exclusive to Safari and d ...

Verifying dynamic number inputs generated using JavaScript values and calculating the total with a MutationObserver

Preamble: I've referenced Diego's answer on dynamic field JS creation and Anthony Awuley's answer on MutationObserver for the created fields. After extensive searching, I found a solution that meets my needs, but it feels somewhat bulky des ...

Count the number of times an iteration occurs in AngularJS/JavaScript

I need assistance with my code snippet below, as I am trying to determine the count of all instances where $scope.rm is equal to "failed" or when $scope.percentage is less than 50. angular.forEach(result1, function (value, key) { $scope.percentage ...