Get the last item of an array VueJS
15,665
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;
}
}
Comments
-
Giesburts almost 2 years
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
-
Giesburts almost 7 yearsI need to get specif 'a' in the array. So not the whole item but only '39'. I will be more specific in my question.
-
Giesburts almost 7 yearsAwesome! Was messing around for so long yet the answer is so easy.. Thanks :)