Skip to content

useSorted

Category
Export Size
366 B
Last Changed
6 months ago

reactive sort array

Demo

input:
output: [ "14", "17", "25", "48", "50", "51", "58", "60", "68", "72", "85", "91", "98" ]
object property sort:
input:
[ { "name": "John", "age": 40 }, { "name": "Jane", "age": 20 }, { "name": "Joe", "age": 30 }, { "name": "Jenny", "age": 22 } ]
output:
[ { "name": "Jane", "age": 20 }, { "name": "Jenny", "age": 22 }, { "name": "Joe", "age": 30 }, { "name": "John", "age": 40 } ]

Usage

ts
import { useSorted } from '@vueuse/core'

// general sort
const source = [10, 3, 5, 7, 2, 1, 8, 6, 9, 4]
const sorted = useSorted(source)
console.log(sorted.value) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(source) // [10, 3, 5, 7, 2, 1, 8, 6, 9, 4]

// object sort
const objArr = [{
  name: 'John',
  age: 40,
}, {
  name: 'Jane',
  age: 20,
}, {
  name: 'Joe',
  age: 30,
}, {
  name: 'Jenny',
  age: 22,
}]
const objSorted = useSorted(objArr, (a, b) => a.age - b.age)

dirty mode

dirty mode will change the source array.

ts
const source = ref([10, 3, 5, 7, 2, 1, 8, 6, 9, 4])
const sorted = useSorted(source, (a, b) => a - b, {
  dirty: true,
})
console.log(source)// output: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Type Declarations

typescript
export type UseSortedCompareFn<T = any> = (a: T, b: T) => number
export type UseSortedFn<T = any> = (
  arr: T[],
  compareFn: UseSortedCompareFn<T>,
) => T[]
export interface UseSortedOptions<T = any> {
  /**
   * sort algorithm
   */
  sortFn?: UseSortedFn<T>
  /**
   * compare function
   */
  compareFn?: UseSortedCompareFn<T>
  /**
   * change the value of the source array
   * @default false
   */
  dirty?: boolean
}
/**
 * reactive sort array
 *
 * @see https://vueuse.org/useSorted
 */
export declare function useSorted<T = any>(
  source: MaybeRefOrGetter<T[]>,
  compareFn?: UseSortedCompareFn<T>,
): Ref<T[]>
export declare function useSorted<T = any>(
  source: MaybeRefOrGetter<T[]>,
  options?: UseSortedOptions<T>,
): Ref<T[]>
export declare function useSorted<T = any>(
  source: MaybeRefOrGetter<T[]>,
  compareFn?: UseSortedCompareFn<T>,
  options?: Omit<UseSortedOptions<T>, "compareFn">,
): Ref<T[]>

Source

SourceDemoDocs

Contributors

Anthony Fu
Kasper Seweryn
Jelf

Changelog

v10.3.0 on 7/30/2023
33a12 - feat: accept getter function as source (#3249)
v9.3.1 on 10/17/2022
feaa1 - feat: new function (#1799)

Released under the MIT License.