Filtering, Sorting, and Searching in Arrays With Vue.js

Improve your user’s access to the relevant data

Thaekeh
The Startup
6 min readDec 3, 2020

--

Cover Image: “Working with arrays in Vue.js”

Full project: CodePen

If you are gonna build a web app, you will probably have to display some data of the user.
To make it easier for users to access the relevant data, we can sort and filter their data.
In this article, I will show you how you can do this with Vue.

So let’s say you are trying to make a web app to display a bunch of different recipes.
These recipes all have different properties.
For a recipe, it’s important to know what ingredients you will need and how much time you need to cook.
To improve the user experience, we will add some filters for these values and we’ll add a search function to look for a specific recipe.

First, we’ll need to create an array of recipes.
So let’s add the following four recipes to our data.

data() {
return {
recipes: [
{title: 'Pizza',
description: 'Yummy pizza for those lazy days',
ingredients: ['Dough', 'Tomato Paste', 'Cheese', 'Bell Pepper', 'Onion'],
cookingTime: 60,
img: 'https://images.unsplash.com/photo-1513104890138-7c749659a591?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80'}, {title: 'Burritos',
description: 'Healthy yet very tasty burritos',
ingredients: ['Burritos', 'Kidney beans', 'Onion', 'Tomato', 'Bell Pepper'],
cookingTime: 30,
img: 'https://images.unsplash.com/photo-1566740933430-b5e70b06d2d5?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80'},
{title: 'Tomato Soup',
description: 'A tasty tomato soup for the cold winter',
ingredients: ['Tomatoes', 'Onion', 'Oregano'],
cookingTime: 45,
img: 'https://images.unsplash.com/photo-1553881781-4c55163dc5fd?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80'},
{title: 'Ice Cream',
description: 'Just because... Ice Cream',
ingredients: ['Whole milk', 'Cream', 'Eggs', 'Sugar'],
cookingTime: 120,
img: 'https://images.unsplash.com/photo-1515037028865-0a2a82603f7c?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=1321&q=80'},
]
}

Every object in this array has the following variables:

  • title
  • description
  • ingredients (array)
  • cookingTime
  • img

In the CodePen I added some HTML and CSS to display our array of objects as cards.

Cards for our recipes
Cards for our recipes

To loop over the information in our array, we use v-for.

The HTML elements we will need for sorting, filtering, and searching in our array is the following:

  • A select tag with two options:
    1. Alphabetically
    2. Cooking Time
  • A button to toggle between ascending and descending.
    I’ve used a font-awesome icon to show a corresponding icon.
  • Two input tags for:
    1. The maximum cooking time, which is a type of number
    2. The search term, which is a type of text

Sorting Our Items

Now that we have our items displayed, we want to add the code to sort these items.
There are a few parameters we want to sort our recipes by:

  • Alphabetically
  • Cooking Time

I’ve picked these two because they use slightly different sorting techniques.

We’ll be using Vue’s computed properties for sorting our array.
In a nutshell, you can see computed properties as methods that get called when a change, that would result in a change in result, occurs.
It’s a great way to keep your data reactive and prevent unnecessarily calling of methods.

Sorting Alphabetically

This is the code for sorting your array by alphabetical order.

Sort by alphabetical order

This is not a lot of code at all, but yet it works.
So what is really happening here?

When you call sort() on an array, it will automatically sort the items by the Unicode value of the first character of each item.
This means that if we have an array like:

['Banana', 'Apple', 'Melon'

After sorting it will look like this:

['Apple', 'Banana', 'Melon']

Keep in mind here that uppercase letters have a higher Unicode value than lowercase letters.
So if you do not first convert your strings to all uppercase or all lowercase, your sorted results will prioritize capitalized letters.

So in our code snippet, we simply compare each item in the array, and if the Unicode value of item a is smaller than that of item b, the sorting method recognizes item a should come before item b.
If value a is bigger than value b, it will move item a behind item b.
If it’s the exact same value we don’t move the items at all.

Array sorted alphabetically in descending order

Like you can see here, the array is now sorted alphabetically in descending order.
We can change this to ascending order by clicking our toggle button in the toolbar.
When you sort by ascending order, we can simply return the sorted array.
If you sort by descending order, you can simply call .reverse() on our array to flip it around.

Sorting Numerically

Sorting numerically uses the sort() method as well.
We’ll expand the code from our previous snippet.

Sorting either alphabetically or numerically

Now our code checks for the current sorting method and acts accordingly.
When comparing numerical values in a sort method, you can simply do:

return a - b

The sort method will see whether the result is either negative, zero, or positive and sort accordingly.
Now that we can sort our array numerically, we’ll move on to filtering our arrays.

Sorting By Boolean Value

If you wish to allow your users to pin or favorite items so they will appear first in your lists, you can sort by Boolean value.
For this, you will need to include a Boolean value to your JSON object:

favorite: false

When a user adds the item to his/her favorites, the Boolean value will be true.
The code to sort by Boolean value will look like this:

Filtering Array Items

When we want to filter items from our arrays, we can use the JavaScript filter() method. (learn more)
This method iterates over all items in the array and compares each item with the parameters you want to filter it by.

In our example, we can filter our items by cooking time.
To do this, we will go over our array and remove the items that have a cooking time of more than our maxCookingTime variable, and return the rest.

Note: after filtering items from your array, you can still sort them by any sorting requirements you have.

As you can see in this code, we will only return the item in the array if the cooking time of the item is smaller than or equal to our maxCookingTime.
You can do a lot of handy things with this, so I will give you another example.

If you want your user to be able to favorite items and only display the favorite items, use this code:

Basically, this just looks at a Boolean value and returns the value.
This means that any Boolean value can be used.
If the Bool is true, then it will include it in the result and otherwise, it will remove it.

Now that we have our basic array filters ready, we can move on to searching for items in our array.

Searching For Items In An Array

Note: we won’t go into any advanced searching but keep it simple.
If you want a deeper exploration of searching methods, leave a comment.

When we want to search for a specific item in an array, we can use the following code:

Here we simply filter the array on whether or not the title of the item includes the search term.
To make this search case-insensitive I first called toUpperCase() on both the item title and the search term.
If you do want it to be case-sensitive, you can simply leave that part out.

Here is all the code we talked about:

You can take a look at this CodePen to play around with the code and see how it works.

If you have any questions, or just enjoyed this article, feel free to leave a comment!

--

--

Thaekeh
The Startup

Software Developer, Environmental Enthusiast