Return the last Array date

Asked

Viewed 282 times

0

Hello, I have a code where I am searching a list of dates.

    for(var i = 0; i < data.list.length; i++){
      if(Date.parse(data.list[i].date) >= dateA){

            console.log(data.list[i].date)


      }          
  }

i wonder if there is possibility to return only the last date of the array.

  • For any array, the last element can be accessed using minhaArray[minhaArray.length - 1]

1 answer

0

Just take the size of the array, its size is the index of its last value

var t = data.list.length;

console.log(data.list[t].date);

I think that solves

But if you want to take the last date and not the last index, you can do a Sort in the array and then take the last index

array.sort();
  • No right kkk, let me explain in a better way, I have a date in my database on 28/03 and another 31/03, I want to get the date closer to today, ie 28/03, in my case would be the last listed in the array

  • then I would use data.list.Sort(); ?

  • Sort sort from smaller to larger, test with Sort and tell me if it worked

  • is that actually I don’t want to order, I just want to list the date closer to today and ignore the other bigger ones

  • Yes, if you order them, the last index will contain the last date, the closest in the case, you said that the data comes from a db, which db would be? Pq no longer brings the last date in the query?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.