代码之家  ›  专栏  ›  技术社区  ›  chrisl-921fb74d

ES6创建一个包含对的数组

  •  0
  • chrisl-921fb74d  · 技术社区  · 6 年前

    给定数据:

    const pairs = [ {name: bob, value: foo}, {name: jane, value: foo}, {name: mary, value: foo}, {name: elizabeth, value: foo}, {name: colin, value: foo}]
    

    希望获得以下输出:

    const pairs = [ 
    
        [{name: bob, value: foo}, {name: jane, value: foo}],
        [{name: mary, value: foo}, {name: elizabeth, value: foo}, {name: colin, value: foo}]
    ]
    

    const result = pairs.reduce((acc, curr, i, array) => {
        const acc = acc.length % 3 === 0 ? acc.slice(acc.length -1, acc.length) : acc.push(curr);
        return acc
    }, []);
    

    有没有一个简单的方法可以做到这一点数组.reduce()?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Przemek    6 年前

    const pairs = [
      {name: 'bob',       value: 'foo'},
      {name: 'jane',      value: 'foo'},
      {name: 'mary',      value: 'foo'},
      {name: 'elizabeth', value: 'foo'},
      {name: 'colin',     value: 'foo'}
    ];
    
    const flooredHalf = parseInt(pairs.length / 2);
    const result = new Array(flooredHalf);
    for (let i = 0; i <= flooredHalf; i += 2) {
      result[i / 2] = pairs.slice(i, (i + 3 === pairs.length ? i + 3 : i + 2));
    }
    
    /* DEMO */
    console.log(JSON.stringify(result));