【问题标题】:How to group all contiguous even numbers into a 2D array?如何将所有连续的偶数分组到二维数组中?
【发布时间】:2022-06-10 21:14:28
【问题描述】:

我有以下数字数组:

[10, 12, 23, 17, 14, 15, 50, 72, 26, 33]

我想将所有出现的偶数组合在一起,如下所示:

[ [ 10, 12 ], [ 14 ], [ 50, 72, 26 ] ]

我可以过滤掉偶数,但我无法将连续的数字组合在一起。我认为reduce 可以在这里使用,但我无法理解如何使用,非常感谢任何帮助。

const nums = [10, 12, 23, 17, 14, 15, 50, 72, 26, 33];
const result = nums.map((n, i) => (n % 2 === 0 ? [n] : []));

console.log(result);

【问题讨论】:

    标签: javascript arrays reduce


    【解决方案1】:

    您可以使用Array.prototype.reduce

    对于每个偶数,执行以下操作:

    1. Push 如果最后一个数字偶数(即奇数),则将一个空数组放入结果数组。

    2. 使用Array.prototype.at 获取结果数组中的最后一个组,然后push 将当前编号放入该组。

    const 
      nums = [10, 12, 23, 17, 14, 15, 50, 72, 26, 33],
      result = nums.reduce((res, num, i) => {
        if (!(num & 1)) {
          if (!i || nums[i - 1] & 1) {
            res.push([]);
          }
          res.at(-1).push(num);
        }
        return res;
      }, []);
    
    console.log(result);

    注意:我使用按位和运算符 (&) 来检查数字是偶数还是奇数,您也可以使用模运算符 (%)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-02
      • 1970-01-01
      • 2021-02-10
      • 1970-01-01
      • 2020-01-18
      相关资源
      最近更新 更多