AndrewLeonardi AndrewLeonardi - 3 months ago 7
jQuery Question

Randomly generate name from Array with zero repeat?

Update: The difference is I'm not trying to make one list I'm trying to make a button that can be clicked and generate a random name

Goal: Click a button and randomly generate a name from an array. I'm trying to be able to click the button and show one name randomly at a time with no repeating names. So far I've been able to randomly select a name but the names still repeat. How could I change my code to avoid any repeating names?

$( ".next").click(function() {
$(".intro").hide()
var people = ["Andrew", "Adam", "Seth", "Mattos", "Eric"];
for(i=0;i<1;i++){
var randomPosition = Math.floor(Math.random() * people.length);
var selected = people.splice(randomPosition,1);
console.log(selected)

$('#person').text(selected)


if ($('#person').text() === "Mattos"){
$("#selectedPerson").text("Mattos")
}
if ($('#person').text() === "Andrew"){
$("#selectedPerson").text("Andrew")
}
if ($('#person').text() === "Eric"){
$("#selectedPerson").text("Eric")
}

if ($('#person').text() === "Seth"){
$("#selectedPerson").text("Seth")
}
if ($('#person').text() === "Adam"){
$("#selectedPerson").text("Adam")
}
}
});

Answer

The problem is that you're creating the array every time you enter the function. So splicing the name out of the array has no effect, because you'll refill it the next time. You need to move the array initialization out of the function.

Other issues: splice() returns an array, not a single element, even if you're only splicing out 1 element from the array. You don't need a for() loop if you're only looping 1 time. All the if statements were unneeded, since you're just assigning the same strings in all cases.

And you should check for the case where you've run out of names.

var people = ["Andrew", "Adam", "Seth", "Mattos", "Eric"];

$( ".next").click(function() {
    $(".intro").hide();
    if (people.length == 0) { // No names left to show
        return;
    }
    var randomPosition = Math.floor(Math.random() * people.length);
    var selected = people[randomPosition];
    people.splice(randomPosition,1);
    console.log(selected)

    $('#person,#selectedPerson').text(selected);
});
Comments