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.
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.
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);