🎓 A1Learner
🔍
0 of 50 lessons completed

Sorting Lists in Vue

Sorting a list puts its items in order, like A to Z. A computed value builds the sorted list from the first list.

Sort a copy

The copy takes the sort, and the first list is untouched.

const sorted = computed(() => [...fruits.value].sort())

Show the sorted list

The sorted list starts with Apple.

<li v-for="fruit in sorted" :key="fruit">{{ fruit }}</li>

Show the first list too

The first list still starts with Cherry.

<li v-for="fruit in fruits" :key="fruit">{{ fruit }}</li>

Example

<script setup>
import { ref, computed } from 'vue'
const fruits = ref(['Cherry', 'Apple', 'Banana'])
const sorted = computed(() => [...fruits.value].sort())
</script>
<template>
  <div>
    <h2>First order</h2>
    <ul>
      <li v-for="fruit in fruits" :key="fruit">{{ fruit }}</li>
    </ul>
    <h2>Sorted</h2>
    <ul>
      <li v-for="fruit in sorted" :key="fruit">{{ fruit }}</li>
    </ul>
  </div>
</template>

Key points

  • Array.sort is a method that puts an array in order.
  • sort changes the array it runs on. Run it on a copy here.
  • The spread syntax makes a copy, so [...fruits] is a new array with the same items.
  • The computed value sorts the copy, and the first list keeps its first order.
  • The page can show both lists, so the change in order is easy to see.

In this example, fruits is a ref that holds Cherry, Apple, and Banana. sorted is a computed value that sorts a copy of fruits. The page shows both lists. The first list still starts with Cherry. The sorted list starts with Apple. The copy keeps the first list in its first order.

Note

Sorting words puts them in A to Z order.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Why does the sorted list use [...fruits] instead of fruits?