Sort data in Alpine JS without writing any JavaScript 🦜
npm install alpinejs-sortSort data in Alpine JS without writing any JavaScript 🦜
``html
defer
src="https://unpkg.com/alpinejs-sort@latest/dist/sort.min.js"
>
`
`shell
yarn add -D alpinejs-sort
npm install -D alpinejs-sort
`
`js
import Alpine from 'alpinejs'
import sort from 'alpinejs-sort'
Alpine.plugin(sort)
Alpine.start()
`
In all of these examples asc is the default, but this can be changed through
Alpine JS.
_You can move the x-sort onto the same element as the x-data if you wish._
` html`
Here we simply pass asc or desc as the array does not contain objects.
`html
x-data="{
items: [
{ title: 'D post' },
{ title: 'A post' },
{ title: 'C post' },
{ title: 'B post' }
],
type: 'asc.title'
}"
>
Here we pass
asc.title or desc.title as we want to sort on an object
property. This translate to:> Sort by asc or desc order based on the value of
title.$3
`html
x-data="{
items: [
{ title: { main: 'D post', sub: 'D' } },
{ title: { main: 'A post', sub: 'A' } },
{ title: { main: 'C post', sub: 'C' } },
{ title: { main: 'B post', sub: 'B' } }
],
type: 'asc.title.main'
}"
>
This is the same logic as the previous example.
_The nesting should go as far as you need!
item.title.main.translated.en? Go
for it._Here we pass
asc.title.main or desc.title.main as we want to sort on a
nested object property. This translate to:> Sort by asc or desc order based on the value of
main in the title` object.


