_.zipWith([arrays], [iteratee=_.identity])

64

_.zipWith([arrays], [iteratee=_.identity])
_.zipWith与zip类似,区别是接收iteratee来决定分组的元素怎么连接起来

参数

[arrays] (...Array): 需要处理的数组
[iteratee=_.identity] (Function): 连接分组元素的迭代器方法

返回值

(Array): 返回新的分组好的数组

例子

 

_.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {
  return a + b + c;
});
// => [111, 222]

 

源代码:

import unzipWith from './unzipWith.js'

/**
 * This method is like `zip` except that it accepts `iteratee` to specify
 * how grouped values should be combined. The iteratee is invoked with the
 * elements of each group: (...group).
 *
 * @since 3.8.0
 * @category Array
 * @param {...Array} [arrays] The arrays to process.
 * @param {Function} iteratee The function to combine
 *  grouped values.
 * @returns {Array} Returns the new array of grouped elements.
 * @see unzip, unzipWith, zip, zipObject, zipObjectDeep, zipWith
 * @example
 *
 * zipWith([1, 2], [10, 20], [100, 200], (a, b, c) => a + b + c)
 * // => [111, 222]
 */
//与zip类似,区别是接收iteratee来决定分组的元素怎么连接起来
function zipWith(...arrays) {
  const length = arrays.length//参数数组长度
  let iteratee = length > 1 ? arrays[length - 1] : undefined//最后一个参数是iteratee迭代器
  iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined//迭代器如果不是function,赋值undefined
  return unzipWith(arrays, iteratee)//调用unzipWith处理
}

export default zipWith
unzipWith
import map from './map.js'
import unzip from './unzip.js'

/**
 * This method is like `unzip` except that it accepts `iteratee` to specify
 * how regrouped values should be combined. The iteratee is invoked with the
 * elements of each group: (...group).
 *
 * @since 3.8.0
 * @category Array
 * @param {Array} array The array of grouped elements to process.
 * @param {Function} iteratee The function to combine
 *  regrouped values.
 * @returns {Array} Returns the new array of regrouped elements.
 * @example
 *
 * const zipped = zip([1, 2], [10, 20], [100, 200])
 * // => [[1, 10, 100], [2, 20, 200]]
 *
 * unzipWith(zipped, add)
 * // => [3, 30, 300]
 */
//和unzip方法类似,多接收一个iteratee参数,在逆转zip操作之后对结果数组调用iteratee处理处最终结果
function unzipWith(array, iteratee) {
  if (!(array != null && array.length)) {//如果数组为空或者数组没有长度,返回空数组
    return []
  }
  const result = unzip(array)//调用unzip获取到zip逆转后的结果
  return map(result, (group) => iteratee.apply(undefined, group))
  //遍历结果数组,用iteratee处理生成最终的结果
}

export default unzipWith

 

posted @ 2018-10-27 00:13  hahazexia  阅读(398)  评论(0)    收藏  举报