跳到主要内容

useArrayDifference

分类
导出大小
301 B
上次更改
3 个月前

响应式地获取两个数组的差异。

默认情况下,它返回第一个数组与第二个数组的差异,即 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 选项来获取对称差

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
NoiseFan
Robin
IlyaL
wangliangxin
chirokas
simpleoo0o
Lee Dogyeong
丶远方

更新日志

v13.6.0
d32f8 - refactor: 为所有纯函数添加 @__NO_SIDE_EFFECTS__ 注释 (#4907)
v13.1.0
c1d6e - feat(shared): 确保返回类型存在 (#4659)
v12.8.0
7432f - feat(types): 废弃 MaybeRefMaybeRefOrGetter,转而使用 Vue 的原生类型 (#4636)
v12.3.0
59f75 - feat(toValue): 废弃 @vueuse/shared 中的 toValue,转而使用 Vue 的原生函数
46fdc - feat: 新增 symmetric 选项 (#4146)
0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)

根据 MIT 许可证发布。