I am trying to create a logic for quote app. There is an array that has objects as elements, further that object that has two keys, quotes and author. Now I want when a button (New Quote) clicked, it selects a random quote from quotesArray with his author.
I am facing two problems here,
Problem 1: I am unable to select a random element from quotes key that nested inside an object.
Problem 2: It selects an author randomly not from that same object that has quotes array.
I hope I am clear.
Here are my codes.
HTML code:
<div class="quote-app">
<div class="quote">Quote</div>
<div class="author">Author</div>
<button class="new-quote">New Quote</button>
</div>
My JS code:
let quote = document.querySelector(".quote"),
author = document.querySelector(".author"),
newQuote = document.querySelector(".new-quote");
let quotesArray = [
{
author: "Author1",
quotes: ["a", "b", "c", "d", "e"]
},
{
author: "Author2",
quotes: ["f", "g", "h"]
},
{
author: "Author3",
quotes: ["i", "j"]
},
{
author: "Author4",
quotes: ["k", "l", "m", "n"]
}
];
newQuote.addEventListener("click", function(){
quote.innerHTML = quotesArray[Math.floor(Math.random() *
quotesArray.length)].quotes[Math.floor(Math.random() * quotes.length)];
author.innerHTML = quotesArray[Math.floor(Math.random() *
quotesArray.length)].author;
});
when I write (Math.random() * 3) instead of quotes.length, it works fine but I want to select the element from quotes.length not the particular length.
I will be if someone can sort out my problem.