In my lab assignment, I was given an array of names like this:
const names = ['Peter', 'Andrew', 'Ann', 'Mark', 'Josh', 'Sandra', 'Cris', 'Bernard', 'Takesi'];
The task is to write a function that will create an array containing subarrays with three names each:
`[['Peter', 'Andrew', 'Ann'], ['Mark', 'Josh', 'Sandra'], ['Cris', 'Bernard', 'Takesi']]`
I attempted it and ended up with one flat array as follows:
function sortByGroups() {
let arr = [];
for (let i = 0; i < names.length; i = i + 3){
for (let j = i; j < i + 3; j++){
if (j < i + 2){
arr += `${names[j]},`;
} else {
arr += `${names[j]}`;
}
}
return arr.split(',')
}
}
console.log(sortByGroups()); // [ 'Peter', 'Andrew', 'Ann' ]
However, I am stuck on how to further manipulate the data to achieve the desired output:
[['Peter', 'Andrew', 'Ann'], ['Mark', 'Josh', 'Sandra'], ['Cris', 'Bernard', 'Takesi']]