zl程序教程

您现在的位置是:首页 >  其它

当前栏目

_.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