简体   繁体   中英

Issue with for loop in iterating the last 5 objects in reverse order

I have one json array. Now I need to display on my UI such that it displays only the last 5 json objects in reverse order. If the length of the array is less than 5 it should display all those same in reverse order.

Now I was successful in displaying the last 5 if the length is greater than 5. But if the array size is less than 5 my logic is not working. How can we fix this. Can someone help

for (var i = response.length - 1 ; i >= response.length-5 ; --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;
}

You could check if i is greater or equal as zero as well.

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

or use a variable for the lower bound

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

for (var i = response.length - 1; i >= min; --i) {
Add a condition for your case
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 + '&nbsp;' + response[i].amount + '&nbsp;' + response[i].description;
}

Use reverse() and splice() functions respectively

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

Now this response object will contain last five records in reverse order. now you just need to iterate this.

for(i=0;i<response.lenth;i++)
{
     //Your code here
}

Here is the one of the solution. I have updated original array, where you can keep original array as it is :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM