Searching within lists with Alpine.js
a quick script for matching patterns in arrays
// updated 2025-09-24 17:10
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:
searchprovides a state variable for the current search queryitemsprovides 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
thisto refer to the entire object withinx-data- note how we use
thiswhenever 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
searchquery
- 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-modelwith the <input> tag to bind thesearchproperty ofx-data - we use an unordered list
- inside the list we use a <template> tag that represents each item in this dynamic list
itemrefers to each item (a string element) in the filtered array (filteredItems) that changes with each search- the
:keyattribute should provide a unique identifier for debugging purposes
- each item then displays a list item using an
x-textdirective- the value of
x-textthen displays the item
- the value of
- inside the list we use a <template> tag that represents each item in this dynamic list