Return last index of Array

Asked

Viewed 1,913 times

0

I have the following code that will bring me an undetermined list; for example 5 items. I would like to return only the last item from the list.

for(var i = 0; i < data.list.length; i++){

      if(Date.parse(data.list[i].date) >= dateA){
          console.log(data.list[i].date);

      }

3 answers

3

Given that the array starts at 0, you just have to access the position related to the size of the array minus one:

const valores = [1, 2, 3, 4, 5];

console.log("O último valor é:", valores[valores.length - 1]);

This way you do not depend on third party libraries and do not modify the array original, always accessing the last value with a time O(1), that is, constant regardless of the size of the array.

  • the last of the date.list[i], look in my codeThat will list only the dates larger than today’s date for example day 28/03 and 30/03 and I want to get the 30/03 that is last in the list

  • @Fernandoantunes then, just analyze the logic and adapt it to your need. If you need the last element of a array, that’s how it does it, regardless of what the array.

1

Seeing that his list is an array, you don’t even need to loop for to return the last item, just use the method reverse() and take the first index [0]:

var data = {
   list: [
      {
         date: "2018/01/10"
      },
      {
         date: "2018/01/09"
      },
      {
         date: "2018/05/01"
      }
   ]
}

console.log(data.list.reverse()[0].date); // retorna o último valor: 2018/05/01

Can use .pop() also:

var data = {
   list: [
      {
         date: "2018/01/10"
      },
      {
         date: "2018/01/09"
      },
      {
         date: "2018/05/01"
      }
   ]
}

console.log(data.list.pop().date); // retorna o último valor: 2018/05/01

Note: the problem is that the .pop() will also remove the last item from the array. So do not use it if you want to maintain the integrity of the array.

  • i need to return only the last index of that within the data.list[i]. date not of the data.list

  • The last of each index?

  • the last of the date.list[i], look in my codeThat will list only the dates larger than today’s date for example day 28/03 and 30/03 and I want to get the 30/03 that is last in the list

  • Got confused because in the for you put data.list.length, that is, is looking for an item within data.list

1

You can use _.last as explained here:

data = [1,2,3]
last = _.last(data)
alert(last)
  • A curiosity: what would be the _?

  • @dvd is basically the equivalent of $ jQuery from the library loadash. A namespace object for library functions.

  • @Andersoncarloswoss humm... I tried to rotate here and gave Uncaught ReferenceError: _ is not defined

  • @Andersoncarloswoss Ah tah.. I looked at the link indicated... is a library...

Browser other questions tagged

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