Skip to content

useArrayDifference

Category
Export Size
251 B
Last Changed
5 days ago

Reactive get array difference of two arrays.

By default, it returns the difference of the first array from the second array, so call A \ B, Relative Complement of B in A.

You can pass the symmetric option to get the Symmetric difference of two arrays A △ B.

Demo

Usage

Use with reactive array

tsx
import { 
useArrayDifference
} from '@reause/shared'
import {
useState
} from 'react'
const [
list1
,
setList1
] =
useState
([0, 1, 2, 3, 4, 5])
const [
list2
,
setList2
] =
useState
([4, 5, 6])
const
result
=
useArrayDifference
(
list1
,
list2
)
// result: [0, 1, 2, 3]
setList2
([0, 1, 2])
// result: [3, 4, 5] on the next render

Use with reactive array and use function comparison

tsx
import { 
useArrayDifference
} from '@reause/shared'
import {
useState
} from 'react'
const [
list1
,
setList1
] =
useState
([{
id
: 1 }, {
id
: 2 }, {
id
: 3 }, {
id
: 4 }, {
id
: 5 }])
const [
list2
,
setList2
] =
useState
([{
id
: 4 }, {
id
: 5 }, {
id
: 6 }])
const
result
=
useArrayDifference
(
list1
,
list2
, (
value
,
othVal
) =>
value
.
id
===
othVal
.
id
)
// result: [{ id: 1 }, { id: 2 }, { id: 3 }]

Symmetric Difference

This hook also supports Symmetric difference by passing the symmetric option.

tsx
import { 
useArrayDifference
} from '@reause/shared'
import {
useState
} from 'react'
const [
list1
,
setList1
] =
useState
([{
id
: 1 }, {
id
: 2 }, {
id
: 3 }, {
id
: 4 }, {
id
: 5 }])
const [
list2
,
setList2
] =
useState
([{
id
: 4 }, {
id
: 5 }, {
id
: 6 }])
const
result
=
useArrayDifference
(
list1
,
list2
,
(
value
,
othVal
) =>
value
.
id
===
othVal
.
id
,
{
symmetric
: true }
) // result: [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 6 }]

Type Declarations

ts
export interface UseArrayDifferenceOptions {
    symmetric?: boolean;
}

export type UseArrayDifferenceReturn<T = any> = T[]

export function useArrayDifference<T>(list: readonly T[], values: readonly T[], key?: keyof T, options?: UseArrayDifferenceOptions): UseArrayDifferenceReturn<T>

export function useArrayDifference<T>(list: readonly T[], values: readonly T[], compareFn?: (value: T, othVal: T) => boolean, options?: UseArrayDifferenceOptions): UseArrayDifferenceReturn<T>

Source

Source · Demo · VueUse

Contributors

hairyf

Changelog

v0.1.0 on
90a28 - fix(shared): resolve useArrayDifference audit findings (#714)
8fddc - chore!: remove all Vue-only Maybe* types and getter unions, adopt React Ref (#462)

Released under the MIT License. v0.1.8