James
James

Reputation: 21

Fetching a value from a result?

So I am fetching values from chuck norris api. I am able to fetch and present values when given one value such as when using random event from the api. My question is, how can I present a value given to me when there is more than one value displayed in a list?

let topic = args.join(" "); //defines topic set as varliable to use in query search

fetch(`https://api.chucknorris.io/jokes/search?query=${topic}`).then(result => result.json());
const { sub } = await fetch(`https://api.chucknorris.io/jokes/search?query=${topic}`).then(result => result.json());

if(topic !== " ") { return message.channel.send(sub)};

Upvotes: 0

Views: 97

Answers (2)

raychz
raychz

Reputation: 1175

Easiest way to choose a random value from an array of items is to do the following:

const randomItem = allItems[Math.floor(Math.random() * allItems.length)];

Upvotes: 0

Jacob
Jacob

Reputation: 78848

It sounds like you're asking how to pick one item at random from an Array. Math.random gives you a random number between 0 and 1. How can you convert this to a random index in an Array? Multiply by the size of your Array first, then round down with Math.floor:

const response = await fetch(`https://api.chucknorris.io/jokes/search?query=${topic}`);
const jokes = await response.json();
const randomIndex = Math.floor(Math.random() * jokes.length);
const randomJoke = jokes[randomIndex];
return message.channel.send(randomJoke)

Upvotes: 1

Related Questions