Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the last item of an array VueJS

I am working on a small VueJS webapp. I would like to output data from my array to the view but it has to be the last item of an array and of that last item the second item which is a and in my example equel to 39. I don't know how I can recieve that one.

HTML

<p>The last number in the array (a) is {{userLastCount}} </p>

Javascript/Vue

data () {
    return {

        event: 'Custom event',
        userLastCount: 0,


        lineData: [
            { time: '2017-05-01 15:00', a: 0 },
            { time: '2017-05-01 16:00', a: 12 },
            { time: '2017-05-01 17:00', a: 23 },
            { time: '2017-05-01 18:00', a: 28 },
            { time: '2017-05-01 19:00', a: 39 },
        ]

    }
},

components: {
    DonutChart, BarChart, LineChart, AreaChart
},

created() {
    this.userLastCount = //equal to 39
}

I would like to output the last value of 'a' of the lineData object and assign it to a data string which I can output to the view. So, now the last 'a' = 39. But if I add another row in my object It has to be that one that is assigning to this.userLastCount

like image 396
Giesburts Avatar asked Sep 19 '25 03:09

Giesburts


1 Answers

The last item of an array is arr[arr.length - 1]. You can use a computed to have that value always set for you, rather than maintaining a data item yourself:

computed: {
  userLastCount() {
    return this.lineData[this.lineData.length - 1].a;
  }
}
like image 170
Roy J Avatar answered Sep 20 '25 17:09

Roy J