Searching within lists with Alpine.js
a quick script for matching patterns in arrays
// updated 2025-09-19 09:39
For an Alpine.js app, if we have a list (i.e. a JavaScript array) of items, then we can search through the list by making use of properties within the x-data
directive object:
1<div
2 x-data="{
3 search: '',
4
5 items: ['aa', 'bb', 'ba', 'ab'],
6
7 get filteredItems() {
8 return this.items.filter(
9 item => item.includes(this.search)
10 )
11 }
12 }"
13>
14 ...
15</div>
So breaking down the above x-data
directive:
search
provides a state variable for the current search queryitems
provides a state variable for the list (an array of strings)get filteredItems()
provides a method to return the results of a search on a list- we use the keyword
this
to refer to the entire object withinx-data
- note how we use
this
whenever we want to reach any other property or method in this object
- note how we use
- we then filter on the array with
this.items.filter(...)
- this higher-order filter method finally looks at each item in the array
- ...and returns any item that contains (includes) the same characters as in the
search
query
- we use the keyword
Demo
We can try it in this demo (try it with CAPS LOCK on or with initial spaces!):
First notice that we use the following just for user experience:
toLowerCase()
to avoid case-sensitivitytrim()
to remove whitespace
Also note the following:
- we use
x-model
with the <input> tag to bind thesearch
property ofx-data
- we use an unordered list
- inside the list we use a <template> tag that represents each item in this dynamic list
item
refers to each item (a string element) in the filtered array (filteredItems
) that changes with each search- the
:key
attribute should provide a unique identifier for debugging purposes
- each item then displays a list item using an
x-text
directive- the value of
x-text
then displays the item
- the value of
- inside the list we use a <template> tag that represents each item in this dynamic list