I have one lab where is given:
const names = ['Peter', 'Andrew', 'Ann', 'Mark', 'Josh', 'Sandra', 'Cris', 'Bernard', 'Takesi'];
It’s required to create function that will create array which will contain other arrays with three names:
`[['Peter', 'Andrew', 'Ann'], ['Mark', 'Josh', 'Sandra'], ['Cris', 'Bernard', 'Takesi']]`
I did below and it gives me one array , as expected:
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' ]
but after I don’t know what to do to get the required result:
[['Peter', 'Andrew', 'Ann'], ['Mark', 'Josh', 'Sandra'], ['Cris', 'Bernard', 'Takesi']]
3
Answers
From a list of integers i=0,1,2, you can get elements 3i to 3i+2
A for-loop based version might be this:
A fully functional approach is here
It creates the list of integers first, and then maps the entries into it.
lastUsedIndex
to store value of last element inserted in last group, and just making sure next time that current index should be greater thanlastUserIndex
.['that data',undefined,undefined]
.You can use
Array.reduce
to iterate the return the resulting array.