如何使_lodash。邮政与更少的代码

时间:2022-03-24 21:31:50

Definition: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.

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

Current Solution:

目前的解决方案:

 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 Case:

测试用例:

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],
  ])
})

I want to get a better way to achieve zip, current solution is ugly

我想找到更好的实现zip的方法,目前的解决方案很难看

1 个解决方案

#1


0  

See Destructuring Assignment and Array.prototype.map for more info.

参见析构赋值和Array.prototype。地图更多信息。

// 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]]

#1


0  

See Destructuring Assignment and Array.prototype.map for more info.

参见析构赋值和Array.prototype。地图更多信息。

// 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]]