Search code examples
javascriptarraysclassobject

Push new objects created from class into array - JavaScript


I've got a class Student with constructor for name of student. I want to easily generate an array of all students with names 'Student 1', Student 2', ...

I was thinking two for loops:

    function generateNames (studentAmount) {
        for (let i = 0; i < studentAmount; i++) {
            generateNicknames.push('Student' + [i + 1])
        }
        return generateNicknames
    }
    
    let allStudents = [] 
    function generateStudents(arrayOfNames) {
        for (let j = 0; j < arrayOfNnames.length; j++) {
            allStudents.push(new Student(arrayOfNames[j]))
        }
        return allStudents
    }

The first one generates an array with ['Student 1', 'Student 2', ] etc. But the second one only generates '[Student, Student, Student...]

Any suggestions?


Solution

  • First, I have moved the empty array inside the first function: it is always a good idea to keep all variables you are modifying inside the function if possible. This way you will avoid collisions and unexpected behaviour more easily.

    Finally, I have also refactored your second function to make it shorter using map() function.

    The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

    function generateNames(studentAmount) {
      const nicknames = []; // the array is now inside the function
      for (let i = 0; i < studentAmount; i++) {
        nicknames.push(`Student${i + 1}`);
      }
      return nicknames;
    }
    
    function generateStudents(arrayOfNames) {
      return arrayOfNames.map((name) =>  new Student(name));
    }
    
    const names = generateNames(10);
    const students = generateStudents(names);
    console.log(students) // [Student {name: 'Student1', ...}, ... Student {name: 'Student10', ... }]