_.zip([arrays])
61
_.zip([arrays])
_.zip方法接收多个数组,取每个参数数组的第一个元素作为一个数组,这个数组是结果数组的第一个元素;取每个参数数组的第二个元素作为一个数组,这个数组是结果数组的第二个元素;后面以此类推
参数
[arrays] (...Array): 处理的数组
返回值
(Array): 返回分组后的数组
例子
_.zip(['a', 'b'], [1, 2], [true, false]); // => [['a', 1, true], ['b', 2, false]]
源代码:
import unzip from './unzip.js' /** * Creates an array of grouped elements, the first of which contains the * first elements of the given arrays, the second of which contains the * second elements of the given arrays, and so on. * * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @returns {Array} Returns the new array of grouped elements. * @see unzip, unzipWith, zipObject, zipObjectDeep, zipWith * @example * * zip(['a', 'b'], [1, 2], [true, false]) * // => [['a', 1, true], ['b', 2, false]] */ //zip方法接收多个数组,取每个参数数组的第一个元素作为一个数组,这个数组是结果数组的第一个元素;取每个参数数组的第二个元素作为一个数组,这个数组是结果数组的第二个元素;后面以此类推 function zip(...arrays) { return unzip(arrays) } export default zip
unzip
import filter from './filter.js' import map from './map.js' import baseProperty from './.internal/baseProperty.js' import isArrayLikeObject from './isArrayLikeObject.js' /** * This method is like `zip` except that it accepts an array of grouped * elements and creates an array regrouping the elements to their pre-zip * configuration. * * @since 1.2.0 * @category Array * @param {Array} array The array of grouped elements to process. * @returns {Array} Returns the new array of regrouped elements. * @see unzipWith, zip, zipObject, zipObjectDeep, zipWith * @example * * const zipped = zip(['a', 'b'], [1, 2], [true, false]) * // => [['a', 1, true], ['b', 2, false]] * * unzip(zipped) * // => [['a', 'b'], [1, 2], [true, false]] */ //unzip会把zip方法的结果转换回初始状态 //zip方法接收多个数组,取每个参数数组的第一个元素作为一个数组,这个数组是结果数组的第一个元素;取每个参数数组的第二个元素作为一个数组,这个数组是结果数组的第二个元素;后面以此类推 function unzip(array) { if (!(array != null && array.length)) {//如果数组为空,或者数组没有长度,返回空数组 return [] } let length = 0//结果数组的长度 array = filter(array, (group) => {//用filter遍历array,过滤掉非array-like对象,并且计算出结果数组的长度 if (isArrayLikeObject(group)) { length = Math.max(group.length, length) return true } }) let index = -1//循环索引 const result = new Array(length)//结果数组 while (++index < length) {//结果数组的元素是分别从每一个array元素取出对应的索引值 result[index] = map(array, baseProperty(index)) } return result } export default unzip