In this Vue.js tutorial, I’ll show you how to get the last item of an array using the slice()
method.
You can use the slice(-1)
method, which returns a part of an array, without modifying the original array. Which makes it better than using the pop()
method, which changes the length of the original array.
Array.slice(-1) example
Suppose you have an array of items: YouTube, Spotify, Facebook and Snapchat. If you want to get the last item (Snapchat) and do something with it (e.g. delete it), you can use the Array.prototype.slice() method.
new Vue({
el: "#app",
data: {
items: ['YouTube', 'Spotify', 'Facebook', 'Snapchat']
},
computed: {
lastItem() {
return this.items.slice(-1)[0]
}
}
})
HTML:
<div id="app">
<h2>Items:
<ul>
<li v-for="item in items">
{{ item }}
</li>
</ul>
<br>
<h2>Last item:
<ul>
<li>{{ lastItem }}
</ul>
</div>
Output:
Items:YouTube
Spotify
Snapchat
Last item:
Snapchat
Array of objects example
You can also use the slice()
method with an array of objects.
In this example we have an array of projects. Each project has a title and project status (is_active).
We get the last project using the slice()
method in the computed property lastItem()
and then display it in the template.
new Vue({
el: "#app",
data: {
items: [
{ title: "Project S", is_active: false },
{ title: "Project E", is_active: false },
{ title: "Project Y", is_active: true },
{ title: "Project X", is_active: true }
]
},
computed: {
lastItem() {
return this.items.slice(-1)[0]
}
}
})
HTML:
<div id="app">
<h2>Projects:
<ul>
<li v-for="item in items">
<label>
{{ item.title }}
<span v-if="item.is_active">
(active)
</span>
<span v-else>
(inactive)
</span>
</label>
</li>
</ul>
<br>
<h2>Last project:
<ul>
<li>{{ lastItem.title }}
</ul>
</div>
Output:
Projects:Project S (inactive)
Project E (inactive)
Project Y (active)
Project X (active)
Last project:
Project X
If you find this post useful, please let me know in the comments below.
Cheers,
Renat Galyamov
Want to share this with your friends?
👉renatello.com/vue-js-last-item-in-array
PS: Make sure you check other posts e.g. how to check if a user has scrolled to the bottom in Vue.js, how to do Vue.js polling using setInterval(), JavaScript/Vue.js print object in the console and how to create tabs in Vue.js, check if an item already exists in an array in Vue.js.