How to sort an array in Vue.js/JavaScript/ES6

in Code Write a comment

In this tutorial, you’ll learn how to sort an array by a property value in Vue.js.

Let’s start by creating an array of objects:

todos: [
  { title: "Learn JavaScript", done: false },
  { title: "Learn Vue", done: false },
  { title: "Build something awesome", done: true }

It is a simple todo list. Each task consists of a title and status.

Suppose you want to sort this array by one of its properties. You can do this by using the sort() method of an Array.

The sort() method takes 2 parameters (a, b) and compares them.

Let’s sort our array by title in descending order:

todos.sort((a, b) => (a.title > b.title) ? 1 : -1)

The output will be:

Build something awesome
Learn JavaScript
Learn Vue

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

Renat Galyamov

Want to share this with your friends?

PS: Make sure you check other Vue.js tutorials, e.g. Reverse the order of an array in Vue.js, Detect mobile device in Vue.jsHow to check if an image is loaded in Vue.js.

Incoming search terms:

I developed a Vue.js starter kit that you can order today

Order Vue.js starter kit

Write a Comment