Skip to content

useArrayDifference

类别
导出体积
301 B
上次更改
2 months ago

获取两个数组的差集的响应式结果.

默认情况下,它返回第一个数组与第二个数组的差异,因此调用 A \ B,即 A 中 B 的相对补集

您可以传递 symmetric 选项来获取两个数组的对称差集 A △ B

用法

与响应式数组一起使用

ts
import { 
useArrayDifference
} from '@vueuse/core'
const
list1
=
ref
([0, 1, 2, 3, 4, 5])
const
list2
=
ref
([4, 5, 6])
const
result
=
useArrayDifference
(
list1
,
list2
)
// result.value: [0, 1, 2, 3]
list2
.
value
= [0, 1, 2]
// result.value: [3, 4, 5]

与响应式数组和自定义比较函数一起使用

ts
import { 
useArrayDifference
} from '@vueuse/core'
const
list1
=
ref
([{
id
: 1 }, {
id
: 2 }, {
id
: 3 }, {
id
: 4 }, {
id
: 5 }])
const
list2
=
ref
([{
id
: 4 }, {
id
: 5 }, {
id
: 6 }])
const
result
=
useArrayDifference
(
list1
,
list2
, (
value
,
othVal
) =>
value
.
id
===
othVal
.
id
)
// result.value: [{ id: 1 }, { id: 2 }, { id: 3 }]

Symmetric Difference

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

ts
import { 
useArrayDifference
} from '@vueuse/core'
const
list1
=
ref
([{
id
: 1 }, {
id
: 2 }, {
id
: 3 }, {
id
: 4 }, {
id
: 5 }])
const
list2
=
ref
([{
id
: 4 }, {
id
: 5 }, {
id
: 6 }])
const
result
=
useArrayDifference
(
list1
,
list2
,
(
value
,
othVal
) =>
value
.
id
===
othVal
.
id
,
{
symmetric
: true }
) // result.value: [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 6 }]

类型声明

ts
export interface UseArrayDifferenceOptions {
  /**
   * Returns asymmetric difference
   *
   * @see https://en.wikipedia.org/wiki/Symmetric_difference
   * @default false
   */
  
symmetric
?: boolean
} export type
UseArrayDifferenceReturn
<
T
= any> =
ComputedRef
<
T
[]>
export declare function
useArrayDifference
<
T
>(
list
:
MaybeRefOrGetter
<
T
[]>,
values
:
MaybeRefOrGetter
<
T
[]>,
key
?: keyof
T
,
options
?: UseArrayDifferenceOptions,
):
UseArrayDifferenceReturn
<
T
>
export declare function
useArrayDifference
<
T
>(
list
:
MaybeRefOrGetter
<
T
[]>,
values
:
MaybeRefOrGetter
<
T
[]>,
compareFn
?: (
value
:
T
,
othVal
:
T
) => boolean,
options
?: UseArrayDifferenceOptions,
):
UseArrayDifferenceReturn
<
T
>

源码

源码文档

贡献者

一纸忘忧
Anthony Fu
Anthony Fu
SerKo
Robin
IlyaL
wangliangxin
chirokas
simpleoo0o
Lee Dogyeong
丶远方

更新日志

d32f8 - refactor: add @__NO_SIDE_EFFECTS__ annotations to all pure functions (#4907)
c1d6e - feat(shared): ensure return types exists (#4659)
7432f - feat(types): deprecate MaybeRef and MaybeRefOrGetter in favor of Vue's native (#4636)
59f75 - feat(toValue): deprecate toValue from @vueuse/shared in favor of Vue's native
46fdc - feat: new symmetric option (#4146)
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)