_.xor([arrays])
Arrays _. XOR
2023-09-11 14:15:02 时间
58
_.xor([arrays])
_.xor取出参数数组中的对称差元素组成一个数组返回
对称差:两个集合的对称差是只属于其中一个集合,而不属于另一个集合的元素组成的集合
参数
[arrays] (...Array): 需要求对称差的数组组成的数组
返回值
(Array): 返回过滤后的元素组成的新数组
例子
_.xor([2, 1], [2, 3]); // => [1, 3]
源代码:
import filter from './filter.js' import baseXor from './.internal/baseXor.js' import isArrayLikeObject from './isArrayLikeObject.js' /** * Creates an array of unique values that is the * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) * of the given arrays. The order of result values is determined by the order * they occur in the arrays. * * @since 2.4.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of filtered values. * @see difference, union, unionBy, unionWith, without, xorBy, xorWith * @example * * xor([2, 1], [2, 3]) * // => [1, 3] */ //取出参数数组中的对称差元素组成一个数组返回 //两个集合的对称差是只属于其中一个集合,而不属于另一个集合的元素组成的集合 function xor(...arrays) { return baseXor(filter(arrays, isArrayLikeObject)) //先将arrays用filter过滤掉不是array-like的元素,然后传递给baseXor处理 } export default xor
baseXor
import baseDifference from './baseDifference.js' import baseFlatten from './baseFlatten.js' import baseUniq from './baseUniq.js' /** * The base implementation of methods like `xor` which accepts an array of * arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of values. */ //xor的基础实现 function baseXor(arrays, iteratee, comparator) { const length = arrays.length//有多少个需要求对称差的数组 if (length < 2) {//如果只有一个数组,就传递给baseUniq做去重后直接返回结果 return length ? baseUniq(arrays[0]) : [] } let index = -1//数组参数的循环索引,也是结果数组的元素索引 const result = new Array(length)//结果数组 while (++index < length) { const array = arrays[index]//当前数组 let othIndex = -1//每一个数组参数的元素的循环索引 while (++othIndex < length) { if (othIndex != index) { //结果数组的元素等于当前array和下一个数组的差集元素 //othIndex循环到下一个的时候,就不和当前array比较,和result[index比较] result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator) } } } return baseUniq(baseFlatten(result, 1), iteratee, comparator) //将结果数组里的数组都展开,然后去重 } export default baseXor
相关文章
- 并发集合(九)使用原子 arrays
- Knockout 新版应用开发教程之Observable Arrays
- [Dart] Manipulate Lists/Arrays in Dart
- [Redux] Reducer Composition with Arrays
- [CoffeeScript] Level 4 Arrays, Objects, Iterations -- Ex
- C++ code:char pointers and char arrays(字符指针与字符数组)
- [Python] Boolean Or "Mask" Index Arrays filter with numpy
- Arrays.asList()返回的ArrayList,这是Arrays里内嵌的一个私有静态类,而并不是java.util.ArrayList类
- Java集合工具类的一些坑,Arrays.asList()、Collection.toArray()...
- LC:4. Median of Two Sorted Arrays
- About Introduction to NumPy Arrays