Reverse the order of an array in Vue.js/JavaScript

in Code Write a comment

In this tutorial, you’ll learn how to reverse an array in Vue.js. There’re multiple ways you can do that in JavaScript. I’ll share the way I do it in my Vue.js projects.

Template solution #1

The easiest solution is to use the slice() and reverse() methods.

<div id="app">
  <h2>List:</h2>
  <ol>
    <li v-for="todo in todos.slice().reverse()">
      {{ todo.text }}
    </li>
  </ol>
</div>
new Vue({
  el: "#app",
  data: {
    todos: [
      { text: "Learn JavaScript", done: false },
      { text: "Learn Vue", done: false },
      { text: "Subscribe to newsletter", done: true }
    ]
  }
})

Output

// List:
// Subscribe to newsletter
// Learn Vue
// Learn JavaScript

As you can see adding <li v-for="todo in todos.slice().reverse()"> changed the order of the list, making the last item become the first.


Hi, I'm Renat 👋

 


Vuex solution #2

If you’re using Vuex to store data (well done!) and want to do some data manipulation you can do that in multiple locations:

Getters

You can reverse the order of the list of items inside the getters object

getters: {
    products: state => {
        return state.products.slice().reverse();
    }
}

and then retrieve it in your component.

computed: {
    products() {
        return this.$store.getters.products;
    }
}

You can also use the Spread operator (three dots in JavaScript) to avoid mutating the state. Using the slice() method is cleaner though, it also reverses array without modifying.

computed: {
    messages() {
      return [...this.$store.getters.products].reverse()
    }
}

If you find this post useful, please let me know in the comments below and subscribe to my newsletter. 

Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/vue-js-reverse-array

PS: Make sure you check other Vue.js tutorials, e.g. How to trigger a mouse click in Vue.js, Detect mobile device in Vue.js, How to check if an image is loaded in Vue.js.

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment

2 Comments