personwholikestocode
personwholikestocode

Reputation: 561

Why isn't an array accepting pushed variables?

I want to create an array of 6 (semi)random trivia category ID numbers received from the jService API. I have my code set up to iterate, pushing a new random category ID into the empty categories array if the ID hasn't already been included.

I have console.logged the variable categories after every iteration for reference. It seems that the ID is being pushed into the array, but then being replaced after every iteration leaving 5 blank array items? I have instead tried creating a nested iteration for the category index number and adding the ID in by doing category[i]=randomCatId , but couldn't get this to work. Shouldn't the push method work fine though? Any help as to why this is happening would be very appreciated. Thanks

let categories = [];

async function getCategoryIds() {
    // save random number from one to 18000 to randomInt
    // randomInt will be used as the "offset" parameter to get a random sequence of categories
    let randomInt = Math.floor((Math.random() * 18000) + 1);
    let res = await axios.get(`http://jservice.io/api/categories?count=100&offset=${randomInt}`);
    // create a loop to iterate until the categories array contains 6 items
    for (i=0;categories.length=6;i++){
        // pull random ID number from the 100 categories pulled from API
        let i= Math.floor((Math.random() * 100) + 1);
        let randomCatId= res.data[i].id;
        console.log("randomCatId =", randomCatId);
        console.log(!categories.includes("randomCatId"));
        // if categories array does not include the randomCatId, add it to the categories array
        if (!categories.includes("randomCatId")){
            categories.push(randomCatId);
        }
        console.log("categories =", categories)
        // categories.push(randomCatId);
    }
}
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Jeopardy</title>
  <link href="https://fonts.googleapis.com/css?family=Copse&display=swap"
        rel="stylesheet">
  <link rel="stylesheet" href="jeopardy.css">
</head>
<body>

<script src="https://unpkg.com/jquery"></script>
<script src="https://unpkg.com/axios/dist/axios.js"></script>
<script src="https://unpkg.com/lodash"></script>
<script src="jeopardy.js"></script>

</body>
</html>

Upvotes: 4

Views: 79

Answers (1)

Edward Romero
Edward Romero

Reputation: 3106

Your for loop is not properly checking for how to end the loop so it will run forever.

Change your for loop to

for (i=0;categories.length<=6;i++)

Upvotes: 3

Related Questions