Problem arises with the for loop when trying to iterate through the final 5 objects in reverse sequence

I have a single JSON array that I would like to display on my user interface by only showing the last 5 JSON objects in reverse order. If the length of the array is less than 5, then all objects should be displayed in reverse order.

Currently, I can successfully display the last 5 objects if the length is greater than 5. However, if the array size is less than 5, my logic does not work as intended. Could someone assist me in fixing this issue?

for (var i = response.length - 1 ; i >= Math.max(response.length-5, 0) ; --i) {
        var date = new Date(response[i].transactiondate);
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var dt = date.getDate();
        response[i].transactiondate = dt + '-' + month + '-' + year;
        outputdata += '<br>' + response[i].transactiondate + ' ' + response[i].amount + ' ' + response[i].description;
}

Answer №1

To improve your code, consider adding a condition for your case like this:
var start = (response.length >=5) ? response.length-5 : 0;

for (var i = response.length - 1 ; i >= start ; --i) {
        var date = new Date(response[i].transactiondate);
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var dt = date.getDate();
        response[i].transactiondate = dt + '-' + month + '-' + year;
        outputdata += '<br>' + response[i].transactiondate + ' ' + response[i].amount + ' ' + response[i].description;
}

Answer №2

To determine if i is greater than or equal to zero, you could also use this approach.

for (var i = response.length - 1; i >= response.length - 5 && i >= 0; --i) {

Alternatively, you can set a variable for the lower limit.

var min = response.length > 5 ? response.length - 5 : 0;

for (var i = response.length - 1; i >= min; --i) {

Answer №3

To achieve this, utilize the functions reverse() and splice()

result = result.reverse();
result = result.splice(5);

The updated response object will now contain the last five records in reversed order. Simply iterate through it as follows:

for (i = 0; i < result.length; i++) {
     //Your logic here
}

Answer №4

Below is a solution that involves updating the original array without altering it:

response = response.slice(-5).reverse();

for (var i = 0 ; i < response.length ; i++) {
var date = new Date(response[i].transactiondate);
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var dt = date.getDate();
        response[i].transactiondate = dt + '-' + month + '-' + year;
        outputdata += '<br>' + response[i].transactiondate + '&nbsp;' + response[i].amount + '&nbsp;' + response[i].description;
}

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

Issue displaying daily data on Google bar chart

Here is the link to my code on JSFiddle: https://jsfiddle.net/vbdy7fLe/1/ I am attempting to utilize a Google column chart to display multiple fields of data organized by date. However, I am facing an issue where the dates 02 Jan 2015 and 04 Jan 2015 are ...

Implement a feature in NextJS where an MP3 file is played upon clicking

Just getting started with JS frameworks and having some trouble with the function syntax. Here's what I have so far: when the button is clicked, it should play a quick audio file specified below the button in the Audio tags. Any suggestions on how to ...

Using implode and explode functions with an array

Here is an array that I am working with: Array( [deselected_attachment_ids] => Array ( [0] => 16883477_12869438 [1] => 16883478_12869439 ) ) The desired output from the array is: array( 12869438, 12869439); This is ...

Learn the step-by-step process of sending an email through the SendGrid API V3 utilizing templates with a comprehensive example

Currently, I am delving into the SendGrid documentation regarding templates and stumbled upon this: You have three options to send transactional templates: Utilizing the SMTP Relay Including the template ID in the templates parameter of the W ...

Activate Bootstrap 5 dropdown exclusively when positioned above its parent element

I am facing an issue with a Bootstrap 5 dropdown menu placed within a div. When I click the icon, the dropdown appears but only those options that overlap the parent div can be hovered/clicked. In the provided screenshot, the 'Action' option fun ...

How about a unique scrolling experience?

Currently, I am attempting to prevent the scroll position from being locked after a single scroll for one second while scrolling down one section at a time. However, I am encountering unexpected behavior. const [nextSection, setNextSection] = useState(&ap ...

Utilizing jQuery's .clone() function to duplicate HTML forms with radio buttons will maintain the radio events specific to each cloned element

I'm currently developing front-end forms using Bootstrap, jQuery, HTML, and a Django backend. In one part of the form, users need to input "Software" information and then have the option to upload the software file or provide a URL link to their hoste ...

What steps should I take to ensure that Jackson properly deserializes into a custom Array implementation that

Incorporating my customized array implementation MyArray<T>, I am seeking a way to inform Jackson of its existence. This will enable Jackson to deserialize a JSON Array into MyArray<T>. Currently, I am encountering the following exception: c ...

Enhancing JSON object usage in a Rails framework for optimal performance

In the framework of my Rails application, I handle a multitude of categories that are linked to various clients. Moreover, the app is designed to accommodate multiple languages seamlessly. One of the key features of the app is the navigation system which ...

Before clicking the submit button, send field values using Ajax

Is it possible to send values using ajax before submitting form data with a submit button? I have the code below. It successfully reaches the success function, but I am unable to retrieve the posted data. Any ideas on how to solve this issue? Your help an ...

Is there a way to verify the existence of a username while avoiding cross browser compatibility issues?

I have created a registration form that dynamically checks existing usernames and email addresses in the database. Unfortunately, it is not functioning properly on FireFox or IE, but works fine on Safari and Chrome. Below is the code snippet: <input ty ...

Learn the process of transmitting information to Thingsboard using HTTP protocol

Currently, I have thingsboard installed on my Windows local machine, and I am looking to send data from a CSV file using an HTTP POST request. In order to achieve this, I am required to develop a JAVA program that can facilitate the sending of data from ...

The map fails to fully display when using d3.js

Currently, I am developing a globe where multiple locations are marked with small circles. These locations provide relevant information through tooltips when the cursor hovers over them. The issue I am facing is that the global map often renders incomplet ...

Tips for managing the three.js player mesh (md2) while incorporating cannon.js physics

Check out a cool demo I recently made the switch to using three.js (coming from a background in OpenGL and C++, so adapting to JavaScript wasn't too difficult). To get a better understanding of how to set things up, I explored various three.js exampl ...

Issues with AngularJS binding and Object HTML tag data attribute in IE11 causing them to not work together

I have a specific application where I need to display files from URLs stored in the database. These files can either be images or PDFs, so I require dynamic binding settings. After some research on the internet, the object tag seemed like a good solution, ...

assign array as the properties of an object

How can I define a specific array (for example, {1, 2, 3, 4}) as a property of an object? This will be the only property. I attempted to achieve this in my class without using an initializing constructor. Here's what I tried: public class Arrays { ...

How can Vue i18n v9 be utilized as a JavaScript object instead of embedding it within the template?

Can Vue and vue-i18n be used with JavaScript objects only, without being included in the template? This code is located in src/boot/i18n.js import { boot } from 'quasar/wrappers' import { createI18n } from 'vue-i18n' import messages fr ...

Generating an ArrayList based on user input values in a Thymeleaf form

I have a form for adding products using HTML and thymeleaf. <form th:action="@{/products/get}" th:object="${form}" method="post"> <div id="fields"> <label for="name&quo ...

Retrieving results from PostgreSQL database using pagination technique

When I'm pagination querying my data from a PostgreSQL database, each request involves fetching the data in this manner: let lastNArticles: Article[] = await Article.findAll({ limit: +req.body.count * +req.body.page, or ...

Exploring the Functionality of PeerJS and Angular4: Controlling Camera and Microphone Access During Streaming

Currently, I am developing an Angular4 app that includes a video call module. The two modules I have created - host and client - are successfully enabling video calls between them. Now, I need to add two buttons for turning the camera and microphone on and ...