用奇数和偶数按值分块数组

Chunking an array by value with odds and evens

我正在尝试创建一个根据长度参数对数字数组进行分组的函数。长度表示每个子数组的最大长度。该代码的工作原理是获取子数组,但我想做的是让它按奇数和偶数排序。

function myFunctionA(myArr1, myVal) {
      newArr = [];
      for ( x = 0; x < myArr1.length; x += myVal) {
        newArr.push(myArr1.slice(x, x + myVal));
      }
      return newArr;
    }
Console.log(myfunction([1,2,3,4,5,6,7,8,9,10],3))

这个returns[[1,2,3],[4,5,6],[7,8,9],[10]]

我想做的是一次遍历每个子数组,直到子数组的长度正确,然后将任何剩余值添加到子数组 array/s

这看起来像

[[1,3,5][2,4,6][7,9][8,10]]

由于 arr 0 和 arr 1 是我们在 console.log 语句中声明的正确长度,因此剩下 7 8 9 和 10。但是由于无法创建完整的子数组并且它们是奇数和偶数,因此它们形成了两个边长为 2 的子数组。

其他示例:

myfunction([1,2,3,4,5,6,7],2)
Should return [[1,3],[2,4],[5,7],[6]]

myfunction([1,2,3,4,5,6,7,8],1)
Should return [[1][2][3][4][5][6][7][8]]

一种可能是先将数字分成偶数和奇数,然后循环遍历,将数字推入一个新数组,在偶数和奇数之间切换。

这不是最干净的代码,但它可以工作。

function myfunction(arr, n) {
  const evenOdd = arr.reduce((acc, e) => {
    const ind = +(e % 2 === 0);
    acc[ind] = acc[ind] || [];
    acc[ind].push(e);
    return acc;
  }, []);

  let ind = 0, res = [[]];

  while (evenOdd[0].length || evenOdd[1].length) {
    for (let i = n; i--;) {
      const val = evenOdd[ind].shift();
      if (val) res[res.length - 1].push(val)
    }
    ind = (ind + 1) % 2
    res.push([])
  }

  res.pop()
  return res;
}

for (const n of [1, 2, 3]) {
  console.log(n,
    myfunction([1, 2, 3, 4, 5, 6, 7, 8], n)
  )
}

您可以采用一个数组来收集所有的奇数和偶数值,然后如果它有零项则推送该组。通过具有所需的大小,创建一个新数组。

function chunkenator(array, size, fn) {
    let groups = [],
        result = [];

    for (let value of array) {
        const group = fn(value);
        if (!groups[group]) groups[group] = [];
        if (!groups[group].length) result.push(groups[group]);
        groups[group].push(value);
        if (groups[group].length === size) groups[group] = [];
    }

    return result;
}

console.log(chunkenator([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3, x => x % 2));
console.log(chunkenator([1, 3, 5, 7, 8, 9, 11, 13, 15], 3, x => x % 2));