intersection 【数组交集】
描述
得到多个数组的交集 v3.0.9+
# 1.示例
import { intersection } from 'sf-utils2'
const a1 = [
{ empId: 1, empName: '蔡徐坤' },
{ empId: 2, empName: '小明' },
{ empId: 3, empName: '小红' },
]
const a2 = [
{ empId: 1, empName: '蔡徐坤' },
{ empId: 4, empName: '小明4' },
{ empId: 5, empName: '小红5' },
]
// 根据属性名转化
intersection([a1, a2], 'empId')
// 输出
[{empId: 1, empName: '蔡徐坤'}]
// 不传属性名
const a1 = [1, 2, 3, '4']
const a2 = [1, 2, 4, 5]
intersection([a1, a2])
// 输出
[1, 2]
intersection(
[
[1, 2, '3', 4],
[1, 2, 3, '4', [1, '4']],
[1, 2, '4']
]
)
=>
[1, 2]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# 2.入参说明
| 参数 | 说明 | 类型 | 是否必填 |
|---|---|---|---|
| val | 值 | Array | -------- |
# 3.源码
源码,点开查看 👈
import arrayToMap from '@/array/arrayToMap'
import uniq from '@/array/uniq'
import isPrimitive from '@/base/isPrimitive'
/**
* 获取多个数组的交集
* @param {Array[]} array
* @param {String|unknown} property
* @return {[string, any]|*[]}
*/
function intersection(array, property) {
const arrayFlatten = array.flat(1) || []
console.log('array', arrayFlatten)
const arrayMap$property = arrayToMap(arrayFlatten, property, { valueType: 'array' })
const [array$0] = arrayFlatten
const result = []
arrayMap$property.forEach((v, k) => {
if (v?.length === array.length) {
result.push(...v)
}
})
if (isPrimitive(array$0)) {
return uniq(result)
}
return result
}
export default intersection
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
上次更新: 2023/06/24, 19:35:48