0

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']]

001
  • 13,291
  • 5
  • 35
  • 66
Ramiz
  • 1
  • 1
    For the inner loop, you need to create a 2nd array, fill it with 3 names, then push that into the outer array. – 001 Apr 06 '23 at 14:25
  • 1
    Also, don't `return` until _after_ the outer loop. – 001 Apr 06 '23 at 14:26
  • Concatenating strings to an array is *really* not what you want to do. Hint: `push()`. – tadman Apr 06 '23 at 14:27
  • https://stackoverflow.com/questions/8495687/split-array-into-chunks might help – cmgchess Apr 06 '23 at 14:28
  • Does this answer your question? [Split array into chunks](https://stackoverflow.com/questions/8495687/split-array-into-chunks) – gog Apr 06 '23 at 14:59

3 Answers3

1

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:

const names = ['Peter', 'Andrew', 'Ann', 'Mark', 'Josh', 'Sandra', 'Cris', 'Bernard', 'Takesi'];

const groupedNames = []
for(let j=0; j<Math.ceil(names.length); j+=3){
groupedNames.push(names.slice(j,j+3))
}
console.log(groupedNames)

A fully functional approach is here

It creates the list of integers first, and then maps the entries into it.

const names = ['Peter', 'Andrew', 'Ann', 'Mark', 'Josh', 'Sandra', 'Cris', 'Bernard', 'Takesi'];

const groupedNames = Array(Math.ceil(names.length/3)).fill(0).map((_,i)=>names.slice(3*i,3*(i+1)))

console.log(groupedNames)
ProfDFrancis
  • 8,816
  • 1
  • 17
  • 26
  • Cool! Your solution is advanced and I will take it to use it in the future. @Nikkkshit's solution is more suitable for my level of knowledge. Thank you. – Ramiz Apr 07 '23 at 05:40
0
  • We are looping through, all names, using temporary variable lastUsedIndex to store value of last element inserted in last group, and just making sure next time that current index should be greater than lastUserIndex.
  • One thing to note, if there will be another extra element in source data then it will add group like ['that data',undefined,undefined].

const names = ['Peter', 'Andrew', 'Ann', 'Mark', 'Josh', 'Sandra', 'Cris', 'Bernard', 'Takesi'];
let lastUsedIndex = -1;
const groupedNames = [];
names.forEach((name, i) => {
  if (i > lastUsedIndex) {
    lastUsedIndex = i + 2;
    groupedNames.push([names[i], names[i + 1], names[i + 2]]);
  }
})

console.log(groupedNames);
Nexo
  • 2,125
  • 2
  • 10
  • 20
0

You can use Array.reduce to iterate the return the resulting array.

const names = ['Peter', 'Andrew', 'Ann', 'Mark', 'Josh', 'Sandra', 'Cris', 'Bernard', 'Takesi'];

const createGroups = (size) => names.reduce((prev, curr, ix) => {
    let arrIx = Math.floor(ix / size);
    prev[arrIx] = [...(prev[arrIx] || []), curr];
  return prev;
}, []);

console.log(createGroups(3));
Nsevens
  • 2,588
  • 1
  • 17
  • 34