JSFiddle - React, Tailwind, and code Playground

by Peer Reynders

JavaScript

const splitInHalf = (a) => chunk(Math.ceil(a.length / 2), a);

const fromIndex = (_, i) => i;
const range20 = Array.from({ length: 20 }, fromIndex);
const range23 = Array.from({ length: 23 }, fromIndex);

console.log(splitInHalf(range20));
console.log(splitInHalf(range23));

function chunk(n, array) {
  if (n < 1) return undefined;

  const result = [];
  for (
    let i = 0, start = 0, end = n;
    start < array.length;
    i += 1, start = end, end += n
  )
    result[i] = array.slice(start, end);

  return result;
}

console.log(chunk(3, range20));
console.log(chunk(4, range20));
console.log(chunk(1, range23));