Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Adding User Input to the Array in JavaScript

Hi everyone,

Here is the problem I'm struggling with:

  1. Ask the user how many students are in the class with a prompt.
  2. Repeat the prompt "enter student's name" as many times as they entered students above. (ex. if 5 was entered, ask for student names 5 times.) Add each students name into an array.
  3. Output the list of student names to the screen by looping through the new array of student names.

I would appreciate any hint for the steps 2 & 3.

Thanks!

2 Answers

As always, Steven Parker has provided a great answer. I have opted for an alternate approach using 'recursion'. Explanation below.

ES6 Node Version

const readline = require('readline')
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: ':'
})

let numberOfStudents
let studentsNames = []

// Helper functions
function isNumeric(n) {
    return !isNaN(parseFloat(n)) && isFinite(n)
}
function ordinalSuffixOf(i) {
    var j = i % 10,
        k = i % 100;
    if (j == 1 && k != 11) {
        return i + "st";
    }
    if (j == 2 && k != 12) {
        return i + "nd";
    }
    if (j == 3 && k != 13) {
        return i + "rd";
    }
    return i + "th";
}

console.log('Press Ctrl + \'C\' to exit at any time')

function askStudentsName() {
    if (studentsNames.length >= numberOfStudents) {
        console.log(`The students are: ${studentsNames.join(', ')}`)
        rl.close()
    } else {
        rl.question(`Please enter the ${ordinalSuffixOf(studentsNames.length + 1)} student's name: `, (answer) => {

            // Store the name in the in an array
            studentsNames.push(answer)

            askStudentsName()
        })
    }
}

// Self invoking function starting the prompt
(function askHowManyStudents() {
    rl.question('How many students are in the class? ', (answer) => {

        // Store the answer in a variable and parse to a number
        numberOfStudents = parseInt(answer)
        if (isNumeric(numberOfStudents)) {
            askStudentsName()
        } else {
            console.log('Your input was not recognized as a number. Please try again.')
            askHowManyStudents()
        }
    })
}())
  • oh nooos, treehouse has not yet added es6 markdown compatibility. Oh well..

Walkthrough

1.Require the necessary things for a node command line interface (CLI)

const readline = require('readline')
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: ':'
})

2.Initialize variables that we will be using throughout. (These are global so that multiple functions can access them, and so that they do not get reset when functions are called more than one time).

let numberOfStudents
let studentsNames = []

3.Get some self explanatory helper functions from GitHub (Credit: DemoUser, Fizer)

function isNumeric(n) {
    return !isNaN(parseFloat(n)) && isFinite(n)
}
function ordinalSuffixOf(i) {
    var j = i % 10,
        k = i % 100;
    if (j == 1 && k != 11) {
        return i + "st";
    }
    if (j == 2 && k != 12) {
        return i + "nd";
    }
    if (j == 3 && k != 13) {
        return i + "rd";
    }
    return i + "th";
}

4.Self invoked function that questions a user for the number of students is fired. If the user input is numeric, it will call the function askStudentsName. If the user input is not numeric, askHowManyStudents will be called from inside itself - AKA 'Recursion' - so that it questions the user for the number of students again.

(function askHowManyStudents() {
    rl.question('How many students are in the class? ', (answer) => {

        // Store the answer in a variable and parse to a number.
        numberOfStudents = parseInt(answer)
        if (isNumeric(numberOfStudents)) {
            askStudentsName()
        } else {
            console.log('Your input was not recognosied as a number. Please try again.')
            //
            askHowManyStudents()
        }
    })
}())

5.When askStudentsName is called, the if statement checks if the the studentsNames array is larger than or equal to the number that the user said there was (So that no more names than specified get pushed to thestudentsNames array). If it is larger, the readline.Interface will be closed (rl.close()). Otherwise, the input will be pushed to the studentsNames array and, again through recursion, the askStudentsName is called from inside itself, so that it asked for the next students name.

Steven Parker
Steven Parker
242,796 Points

Thanks for the nod, Tom. And you've certainly given new meaning to the term "hint" here.   :wink:

I did not expect such a detailed answer when I asked the question! Thanks a lot for your time and effort! ...now I'm going to try to figure it out ;)

Steven Parker
Steven Parker
242,796 Points

For step 2, it sounds like a for loop might be good for asking for input a certain number of times, plus the loop counter would also serve as an array index for storing the input strings.

For step 3, a foreach loop might be expedient for displaying the array contents, but another "for" loop would do it also.

I made a for loop and it does do the work. Now just to figure out how to store the names in the array! Thanks for the answer Steven!