【问题标题】:How to group every 2nd and 3rd items of an array into sub-arrays?如何将数组的每第 2 项和第 3 项分组为子数组?
【发布时间】:2020-06-09 15:34:58
【问题描述】:

我有一个对象数组

const objects = [a, b, c, d, e, f, g ... ]

我希望他们变成

const result = [a, [b, c], d, [e, f], g ... ]

有什么想法吗?

[编辑] 抱歉。这是我的第一篇文章,不知道我必须展示我的尝试。我也不认为我应该得到卑鄙的cmets,做个好人。我在头疼了 4 个小时后解决了它。这是我的解决方案:

const result = []
     const method = array => {
         for (let i = 0; i < array.length; i += 3) {
             const set = new Set([array[i + 1], array[i + 2]])
             if (i !== array.length - 1) {
                 result.push(array[i])
                 result.push(Array.from(set))
             } else {
                 result.push(array[i])
             }
         }
     }

感谢大家的回复!我读了每一本。

【问题讨论】:

  • 你的尝试在哪里?
  • “请做我的功课”
  • 一个快速的谷歌会回答这个问题。从字面上看,前 5 个结果显示了许多不同的选项。

标签: javascript arrays methods javascript-objects


【解决方案1】:

您可以使用 while 循环并推送一个项目或一对项目。

var array = ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
    grouped = [],
    i = 0;

while (i < array.length) {
    grouped.push(array[i++]);
    if (i >= array.length) break;
    grouped.push(array.slice(i, i += 2));
}

console.log(grouped);

【讨论】:

    【解决方案2】:

    您可以使用普通的for 循环和% 模运算符来做到这一点。

    const objects = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
    const result = []
    
    for(let i = 0; i < objects.length; i++) {
      if(i % 3 === 0) {
        const arr = objects.slice(i + 1, i + 3)
        result.push(objects[i])
        if(arr.length) result.push(arr)
      }
    }
    
    console.log(result)

    【讨论】:

      【解决方案3】:

      这是我的解决方案:

      const objects = ["a", "b", "c", "d", "e", "f", "g"];
      let result = [];
      let toGroup = false;
      for(let i = 0; i < objects.length ; i++){
          if(toGroup){
              result.push([objects[i], objects[++i]]);
          }
          else result.push(objects[i]);
          toGroup = !toGroup;
      }
      

      这有一个你没有指定的特殊情况,它不起作用,例如,如果在 objects 里面有 2 个元素,所以我不知道你想在那种情况下做什么

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-31
        • 1970-01-01
        • 1970-01-01
        • 2021-09-16
        • 1970-01-01
        • 2017-07-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多