I'm looking convert an array into an array of subArrays.
An example would be:
let arr = [1, 2, 3, 4, 5, 6, 7, 8]
arr = [[1, 2], [3, 4], [5, 6], [7, 8]]
Now if the length of this array is not divisible by 2
let arr = [1, 2, 3, 4, 5, 6, 7]
arr = [[1, 2], [3, 4], [5, 6], [7]]
My solution to this problem, not very clean IMO
const isPrime = num => {
for (let i = 2; i < num; i++)
if (num % i === 0) return false;
return num > 1;
}
const howToGroupArray = (array) => {
if (array.length === 1) {
return [1, 0] // group of 1 remainder 0
}
else if (!isPrime(array.length) || array.length === 2) {
return [2, 0] // groups of 2 remainder 0
}
else {
return [2, 1] // groups of 2 and a group of 1
}
}
let values = [1,2,3,4,5,6,7]
let newArray = []
let groups = values.forEach((x, i) => {
if ((i === 0 || i % 2 === 0) && (i !== (values.length - 1))) {
newArray.push([x, values[i + 1]])
}
else if ((i % 2 === 1) && (i !== (values.length - 1))) {
null
}
else {
howToGroupArray(values)[1] === 0 ? null : newArray.push([x])
}
})