Home > Software engineering >  Push new objects created from class into array - JavaScript
Push new objects created from class into array - JavaScript

Time:10-24

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?

CodePudding user response:

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', ... }]

CodePudding user response:

Your code seems to work, it can be easily achieved by using array.map. I can propose easier way for the generateStudents function to


function generateStudents(arrayOfNames) {
  return arrayOfNames.map(name => new Student(name))
}
  • Related