skip to Main Content

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


  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)
    Login or Signup to reply.
    • 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);
    Login or Signup to reply.
  2. 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));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search