How can we use forEach on an array or JSON data while sorting by the most recent date?

How can I reverse the order of data in the "forEach" loop so that the latest date is displayed first instead of the oldest to newest?

var json = {
  // JSON data goes here
}

json.TrackingRecord.MovementInformation.Movement.reverse().forEach(function(item) {
  //console.log(item);
  item.MovementDate = moment(item.MovementDate).format('ddd, Do of MMM YYYY');
  item.MovementTime = moment(item.MovementTime).format('hh:mm a');
  $("#movement tbody").prepend("<tr><td>" + item.MovementDate + "</td><td>" + item.MovementTime + "</td><td>" + item.Description + "</td></tr>");
})
<script src="https://cdn.jsdelivr.net/momentjs/2.11.2/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="movement">
  <thead>
    <tr>
      <th>Date</th>
      <th>Time</th>
      <th>Status</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

Answer №1

It's not possible to achieve this with a simple forEach. Here are some alternative methods:

  • If the array is in ascending order, loop through indices from length - 1 down to 0. This method does not alter the original array.
  • If the array is sorted in ascending order, reverse it and then use forEach. Note that this approach modifies the order of elements in the array.
  • If the array is unsorted, first sort it and then apply forEach. This will change the arrangement of elements in the original array.
  • In case the array is unsorted, create an array of indices, sort these indices based on the corresponding values in the original array, and then iterate over the sorted indices using forEach while accessing the array elements. This technique maintains the original array intact.
  • To work with an unsorted array without altering it, make a clone of the array using slice, sort the cloned array, and finally use forEach on the sorted copy. The initial array remains unchanged with this method.

Answer №2

To traverse an array in reverse without modifying it, you can use the method reduceRight:

json.TrackingRecord.MovementInformation.Movement.reduceRight(function(acc, item) {
  // perform actions here
}, null);

Answer №3

You have the option to modify

json.TrackingRecord.MovementInformation.Movement.forEach(function(item) {

by changing it to

json.TrackingRecord.MovementInformation.Movement.reverse().forEach(function(item) {
                                                 ^^^^^^^^^

var json = {
  "TrackingRecord": {
    // Information here
  }
}



json.TrackingRecord.MovementInformation.Movement.reverse().forEach(function(item) {
  // Functionality
})
<script src="https://cdn.jsdelivr.net/momentjs/2.11.2/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="movement">
  <thead>
    <tr>
      <th>Date</th>
      <th>Time</th>
      <th>Status</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

It's important to note that reverse alters the array rather than just returning a reversed array. However, for your specific use case, this behavior is likely desired since the output needs to be in reverse order.

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

Using a combination of functions to ensure synchronicity in JavaScript operations

Here is the function I have created: $scope.saveManualResendDraft = function(todo) { if ($scope.editMode) { updateStartJobManual(); byeSendManualInputDirectly(); } else { console.log('bye'); } }; I have defin ...

Guide to handling multiple forms within a single template using Express

If I have an index.html file containing two tables - "Customers" and "Items", along with two forms labeled "Add customer" and "Add item", how can I ensure that submitting these forms results in a new entry being added to the respective table as well as t ...

Ensure that users must confirm their actions through a message prompt when attempting to exit the website

Looking to add a confirmation box that pops up when someone tries to leave my website. It's important to prevent any information from being lost if they accidentally navigate away. Can you provide detailed instructions on where exactly I should place ...

Tips for formatting RSpec output JSON file with proper indentation

When it comes to running my RSpecs, I execute the following command: RSpec::Core::Runner.run(['spec', '-f', 'json', '--out', 'output.json']) The issue I am facing is that the output in the output.json fil ...

Reaching the maximum request threshold

Currently, I am facing an issue where users are able to upload files from the client side (using Angular 4) to the server (implemented with Spring Boot). The problem arises when a user attempts to upload more than 6 files at once. In such cases, Chrome uti ...

I have implemented a code snippet that verifies if the incoming week aligns with the existing week, triggering an alert accordingly

One of the challenges I faced was checking if a newly created week matched with an existing one, and then displaying an alert. Here's how I approached it: $scope.addWeek = function(type,newWeek,index){ var c = $scope.weekList.length + 1; var ...

Tips for sending additional parameters to an MVC controller without including them in the URL when using the JavaScript window.open method

<a href="#" onclick="openAnchor('<%# DataBinder.Eval(Container.DataItem,"Url") %>', '<%# DataBinder.Eval(Container.DataItem,"infoToSend") %>')"> </a> openAnchor= function (Url, infoToSend) { window.open(Url, ...

Updating file extension name in ReactJS: A quick guide

Looking to modify a file name and extension within the react.js public folder. Changing index.html to index.php https://i.stack.imgur.com/zp1Ga.jpg ** ...

Instructions on activating the standard scrolling function for a specific DIV element

I'm struggling to achieve a specific scrolling effect on my one-page website. I want the initial section to be displayed as a full page, and when the user scrolls down, it should transition to the next section with a full page scroll. However, once th ...

Is there a way to automatically change the value of one input box to its negative counterpart when either of the two input boxes have been filled in?

Consider two input boxes: box1 box2 If a user enters a number in one of the input boxes, we want the value of the other input box to automatically change to the opposite sign of that number. For example: User enters 3 in box1. The value of box2 shoul ...

Using an npm package in client-side JavaScript

I've been exploring client-side GitHub packages recently and came across developers mentioning that the packages can be downloaded using npm. This confuses me as I thought these were client-side JavaScript packages. They also mentioned something about ...

Show the percentage of completion on the progress bar while uploading with AJAX

I'm having trouble updating the current upload value on my progress bar in real-time. I know how to do it when the progress bar has stopped, but I can't get it to update continuously. xhr.upload.onprogress = function(e) { if (e.lengthComputa ...

The JQuery pagination feature fails to function properly once an AJAX load is initiated

I am using jspages.js to implement pagination with jQuery. Everything works fine when the page is initially loaded. However, I encounter an error when the content for pagination is loaded after an ajax call. The plugin does not seem to work as expected. ...

Transitioning away from bower in the latest 2.15.1 ember-cli update

I have been making changes to my Ember project, specifically moving away from using bower dependencies. After updating ember-cli to version 2.15.1, I transitioned the bower dependencies to package.json. Here is a list of dependencies that were moved: "fon ...

Encountered a problem while attempting to remove node version

When I run the command nvm ls -> v4.3.2 system default -> 4.3.2 (-> v4.3.2) node -> stable (-> v4.3.2) (default) stable -> 4.3 (-> v4.3.2) (default) iojs -> N/A (default) Upon running nodejs --version, it returns v0 ...

Tips for utilizing the "Sign In with Apple" feature through Apple JS

For implementing "Sign In with Apple" on a web platform using Apple JS, you can refer to the code example available at this link. Now, the query arises: where can I find the Client ID required for this process? I have tried using the app id identifier fro ...

Sorting two different divisions is an example

I need advice on how to toggle between two divs, A and B, without having to reload the page. Ideally, I would like to have three buttons - one that shows only div A when clicked, another that displays only div B, and a third button that shows both A and ...

Ways to Determine the Height and Width of an Image Once it has been Adjusted for a View

Is there a way to retrieve the height and width of an image after it has been resized for a view? I have images that may vary in original dimensions, but users can resize them as needed. For example, this code from the console gives the client height: do ...

Concealing buttons and Enabling others using ajax

I am facing a situation where I need to modify the behavior of a modal window on my webpage. The modal currently has two buttons for confirmation and cancellation, as shown in the code snippet below. Inside this modal, there is a <div class = "resp"> ...

``There Seems to be an Issue with Loading Content in Tabs

Hey! I'm encountering an issue with my jquery tabs. The first tab content loads fine, but when I select another tab, the content doesn't display. Then, when I try to go back to the first tab, it doesn't load either. Here's the HTML cod ...