-3

I have an array:

names = ['John', 'Smith', 'Sally', 'Jones', 'Jim', 'Doe']

I'm trying to set it as

[['John', 'Smith'], ['Sally', 'Jones'], ['Jim', 'Doe']]

Looking for formula based on the size of the initial array.

Srushti Shah
  • 810
  • 3
  • 17
  • also: [Split array into chunks of N length](https://stackoverflow.com/questions/11318680/split-array-into-chunks-of-n-length) and [How to split a long array into smaller arrays, with JavaScript](https://stackoverflow.com/questions/7273668/how-to-split-a-long-array-into-smaller-arrays-with-javascript) – pilchard May 08 '23 at 13:01
  • [Loops and iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration). – Andy May 08 '23 at 13:05
  • "Split array into chunks of N length" above worked for me thank you. – Eric Morlang May 08 '23 at 13:20

1 Answers1

0

If you want to dynamically calculate the size of subarrays

function smallestDivisorRecursively(n, divisor = 2) {
  if (n <= 1) {
    return "Invalid input. Please enter a positive integer greater than 1.";
  }

  if (n % divisor === 0) {
    return divisor;
  } else {
    return smallestDivisorRecursively(n, divisor + 1);
  }
}

function listToMatrix(list, elementsPerSubArray) {
  let matrix = [],
    i,
    k;

  for (i = 0, k = -1; i < list.length; i++) {
    if (i % elementsPerSubArray === 0) {
      k++;
      matrix[k] = [];
    }

    matrix[k].push(list[i]);
  }

  return matrix;
}

Usage

const arrayFor2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const arrayFor11 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
const arrayFor3 = [1, 2, 3, 4, 5, 6, 7, 8, 9];

const divisorFor2 = smallestDivisorRecursively(arrayFor2.length);
const matrixFor2 = listToMatrix(arrayFor2, divisorFor2);

const divisorFor11 = smallestDivisorRecursively(arrayFor11.length);
const matrixFor11 = listToMatrix(arrayFor11, divisorFor11);

const divisorFor3 = smallestDivisorRecursively(arrayFor3.length);
const matrixFor3 = listToMatrix(arrayFor3, divisorFor3);

console.log(matrixFor2);
console.log(matrixFor11);
console.log(matrixFor3);