如何用更少的代码制作_lodash.zip

时间:2018-03-16 08:12:27

标签: javascript arrays ecmascript-6 lodash

定义:创建一个分组元素数组,第一个元素包含给定数组的第一个元素,第二个元素包含给定数组的第二个元素,依此类推。

当前解决方案:

 const zip = (...arr) => { 
     let maxLength = 0 
     let res = [] 
     for (let el of arr) { 
        maxLength = Math.max(maxLength, el.length) 
     } 
     for (let j = 0; j < maxLength; j++) { 
        const foo = [] 
        for (let n of arr) { 
           foo.push(n[j]) 
        } 
        res.push(foo) 
     } 
     return res 
  }

测试用例:

test(('zip', () => {
  expect(zip([1, 2], [4, 5], [9, 1])).toEqual([[1, 4, 9], [2, 5, 1]])
}

test('zip', () => {
  expect(zip([1, 2, 3], [4, 5, 6])).toEqual([[1, 4], [2, 5], [3, 6]])
})

test('zip', () => {
  expect(zip([1, 2], [], [3, 4, 5])).toEqual([
    [1, undefined, 3],
    [2, undefined, 4],
    [undefined, undefined, 5],
  ])
})

我想获得更好的拉链方式,目前的解决方案很难看

1 个答案:

答案 0 :(得分:0)

有关详细信息,请参阅Destructuring AssignmentArray.prototype.map

// Proof.
const zip = (...args) => [...new Array(Math.max(...args.map(arr => arr.length)))].map((x, i) => args.map((y) => y[i]))

// Proof.
console.log(zip([1, 2], [4, 5], [9, 1])) // [[1, 4, 9], [2, 5, 1]]
console.log(zip([1, 2, 3], [4, 5, 6])) // [[1, 4], [2, 5], [3, 6]]
console.log(zip([1, 2], [], [3, 4, 5])) // [[1, undefined, 3], [2, undefined, 4], [undefined, undefined, 5]]