Return last index of Array

0

I have the following code that will bring me an indeterminate list; for example 5 items. I would like to return only the last item in 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);

      }
    
asked by anonymous 27.03.2018 / 01:25

3 answers

3

Since the array index starts at 0, you only have to access the position relative to the array size minus one:

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

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

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

    
27.03.2018 / 01:47
1

You can use _.last, as explained here :

data = [1,2,3]
last = _.last(data)
alert(last)
    
27.03.2018 / 01:42
1

Seeing that your list is an array, you do not even have to loop for to return the last item, just use the reverse() and get 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

You 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 .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.

    
27.03.2018 / 01:39