I've searched the site for answers but the one's that come up aren't similar/specific to the code that I have written. I don't know how to modify the code so that the quotes don't repeat when the user presses a button to generate another quote.
var quotes = [
{
quote: "\"Don't just exist, live\""
},
{
quote: "\"Try to be a rainbow in someone's cloud\""
},
{
quote: "\"Prove them wrong\""
},
{
quote: "\"Find reasons to smile\""
},
{
quote: "\"You get what you give\""
}
]
var quotebtn = document.getElementById('quote-btn');
var quote = document.querySelector('.quote');
quotebtn.addEventListener('click', () => {
let random = Math.floor(Math.random() * quotes.length);
quote.innerHTML = quotes[random].quote;
})
If the displayed is no longer important and can be deleted. You can do it easily with an array splice.
example:
var quotes = [
{
quote: "\"Don't just exist, live\""
},
{
quote: "\"Try to be a rainbow in someone's cloud\""
},
{
quote: "\"Prove them wrong\""
},
{
quote: "\"Find reasons to smile\""
},
{
quote: "\"You get what you give\""
}
]
var quotebtn = document.getElementById('quote-btn');
var quote = document.querySelector('.quote');
quotebtn.addEventListener('click', () => {
let random = Math.floor(Math.random() * quotes.length);
quote.innerHTML = quotes[random].quote;
quotes.splice(random, 1); // Trim one from the specified index.
})
This should work for you
quotebtn.addEventListener('click', () => {
if(quotes.length) {
let random = Math.floor(Math.random() * quotes.length);
quote.innerHTML = quotes[random].quote;
quotes.splice(random, 1);
} else {
quote.innerHTML = "No more quotes!";
}
})
quotes.splice(random, 1) removes quotes already presented from the array, preventing it from repeating
Once quotes is emptied, the No more quotes! message can be displayed!
You can make another array with the same length as the quotes array and initialize it with zeros. When quote is generated set the new array at the same index as the quote to one which will mean that the quote is already generated. Next time when you generate quote check first if quote is already generated and if it is generate again.
var quotes = [{
quote: "\"Don't just exist, live\""
},{
quote: "\"Try to be a rainbow in someone's cloud\""
},{
quote: "\"Prove them wrong\""
},{
quote: "\"Find reasons to smile\""
},{
quote: "\"You get what you give\""
}];
quotes.sort(() => Math.random() - 0.5);
var quotebtn = document.getElementById('quote-btn');
var quote = document.querySelector('.quote');
var actualQuote = 0;
quotebtn.addEventListener('click', () => {
if(actualQuote>=quotes.length){
quote.innerHTML = "No more quotes";
} else {
quote.innerHTML = quotes[actualQuote % quotes.length].quote;
actualQuote++;
}
});
<button id="quote-btn">Quote</button><br>
<span class="quote"></span>
I just shuffle the quotes at start. At click I display the first, and the next one, etc.
If you want it not to stop after last one just remove the condition and it will cycle trough all. So after the last it will start from the beginning.
Related
i have this code :
con.query(`SELECT * FROM count WHERE default = 'true'`, (err, row) => {
activities = [
`${row[0].members} Members`,
`${row[0].channels} Channels`
];
});
setInterval(() => {
const randomIndex = Math.floor(Math.random() * (activities.length - 1) + 1);
const newActivity = activities[randomIndex];
client.user.setActivity(`${newActivity}`, { type: 'WATCHING' });
}, 10000);
I checked sql everything is ok with mysql and it shows only one of them (it have to change status every 10 second but it doesn't work)
and there is no error
thank you for your help
Remember that arrays in JavaScript start at 0 and the formula to get a random element from an array is array[Math.floor(Math.random() * array.length)];
In your case, you are using the formula activities[Math.floor(Math.random() * (activities.length - 1) + 1)]. Therefore, the array will always get index 1
i got it.
yeah it's true JavaScript start at 0 and formula to get a random element from an array is: var item = activities[Math.floor(Math.random() * activities.length)];
so i had to remove this : const newActivity = activities[randomIndex]; and make the activities like this :
Array(
${${row[0].members} Members,
${${row[0].channels} Channels
);
thank you
I have an array of objects containing lots of data or objects which I import and display in a webpage.
const arr = [
{
question: "What is molecular formula for water?",
options: ["H2O","CO2","H2O","H2O"]
}
]
So Is it possible to write superscript and subscript in a string? To make the numbers superscipted or subscripted while displaying in a webpage.
Note: I have array of around 1000 objects from which only 100 of them are displayed. Some of them may contain superscript whereas some of them may not. Isn't there any simpler way like using alt codes for super scripts and subscripts so that I can directly put it in string.
You could map your array of options to a formatted version of that option by using .replace() to wrap each number in <sup></sup> tags to make it appear as subscript text like so:
const arr = [
{
question: "What is molecular formula for water?",
options: ["H2O","CO2","H2O","H2O"]
}
]
const formatted = arr[0].options.map(elem => elem.replace(/(\d)/g, `<sub>$1</sub>`));
console.log(formatted);
document.body.innerHTML = formatted;
Regex free approach. Supports hydrated salts (like blue vitorl) and balancing numbers. To add hydrated salts, just add a dot
const arr = [{
question: "What is molecular formula for water?",
options: ["H2O", "CO2", "H2O", "H2O"]
},
{
question: "What is the molecular formula for Copper(II) sulphate?",
options: ["H2O", "(CuSO4).5H2O", "H2O2", "D2O"]
}
]
arr.forEach(obj => { // map the first array
let answer = obj["options"].map((options) => { // map all the answers
let op = options.split('').map((data, i) => { // split all the answer strings
if (!isNaN(data)) { // if the data is a number the add <sub> tags to it
if (options.split('')[i - 1] != "." && i != 0) { // if i = 0 is a number then it is a blancing number. Then don't add <sub> tags to it
// also check if the previous string is a dot. Means that has water of crystillization or any other extension
let str = "<sub>" + data + "</sub>"
return str
}else{
return data
}
} else {
return data // else return the string
}
})
return op.join("") // join the string
})
// logic to add data display it
let question = document.createElement("h1") // question
question.innerHTML = obj["question"] // append question content
document.body.appendChild(question) // append the question element to body
let ul = document.createElement("ul") // create unsorted list
answer.forEach((things) => { // for each of the answers
let ali = document.createElement("li") // create a li
ali.innerHTML = things // add answers to the lu
ul.appendChild(ali) // append the li to the ul
})
document.body.appendChild(ul) // append the ul to the body
})
We are just splitting your answers and checking if the data is a number. If it is then we add <sub> tags to it.
To display them, we create elements dynamically and in a loop, we add compounds to a li and then append that to a ul
Make sure to follow the basic chem rules while formatting compounds
Generic example for replacing digits in all values with unicode subscript digits :
var json = JSON.stringify( [ { question: "What is molecular formula for water?", options: ["H2O","CO2","H2O","H2O"] } ] )
var arr = JSON.parse(json, (k, v) => v.trim ? v.replace(/\d/, m => '₀₁₂₃₄₅₆₇₈₉'[m]) : v)
console.log(arr)
document.body.textContent = arr[0].options
I'm creating a lorem ipsum app and I want to click on a button to generate random quotes from a random character. And there will be no mixing of quotes between characters. However, every time I click submit it only shows random quotes from the first character I list in my array. How can I fix this?
const aQuotes = require("./public/quotes/a");
const bQuotes = require("./public/quotes/b");
const cQuotes = require("./public/quotes/c");
const loremIpsum = new GenerateNewText();
function GenerateNewText(){}
GenerateNewText.prototype.getRandomSentence = function() {
const charQuotes =
[
aQuotes,
bQuotes,
cQuotes,
]
for(var i = 0; i < charQuotes.length; i++){
let randomSentence = charQuotes[i][Math.floor(Math.random() * charQuotes[i][Math.floor(Math.random())].length)]
return randomSentence;
}
}
When I run the example above, it'll show a random list of quotes stored in aQuotes with the word "undefined" sprinkled throughout. If I were to move bQuotes to the top of the array, then it will show random bQuotes only, also with the word "undefined". Why is it only showing the results of the first element in the array and why is "undefined" showing (i.e. aQuotes)?
const aQuotes = [
"Lalalalalalalala.",
"Blah blah blah blah.",
"Blank Blank Blank Blank Blank."
]
module.exports = aQuotes;
I tried doing charQuotes[i][Math.floor(Math.random())].length * charQuotes[i][Math.floor(Math.random())].length thinking that it will first randomize the charQuotes array and then randomize the individual a/b/cQuotes array but it ended up returning a block of the number 169. Other "fixes" I've attempted resulted in paragraphs of all undefined text, paragraphs of all NaN, or showing all the quotes for all the characters with the word "undefined" interjected here and there.
How can I randomize the charQuotes array AND the content in my a/b/cQuotes array with every click? And get rid of the weird "undefined" texts that come up?
I am using Node and Express.
You can .map() charQuotes and return a pseudo random value from each input array, and further .sort() the resulting array pseudo randomly
const getRandomSentence = () => {
const charQuotes =
[
["a", "b", "c"],
[1, 2, 3],
[1.5, 2.5, 3.5],
];
const r = charQuotes.map(arr => arr[Math.floor(Math.random() * arr.length)])
.sort(_ => 0.5 - Math.random());
return r.join(" ")
}
console.log(getRandomSentence());
You don't need the for loop. You are entering a loop only to return in the first iteration. That is why you always get the first array of quotes.
GenerateNewText.prototype.getRandomSentence = function() {
const allQuotes =
[
aQuotes,
bQuotes,
cQuotes,
]
const characterQuotes = allQuotes[ Math.floor(Math.random() * allQuotes.length) ]
return characterQuotes[ Math.floor(Math.random() * characterQuotes.length) ]
}
If you want to generate quotes from the same character, you will need to hold the character info in a variable outside the function scope, or in the object instance like the following example:
GenerateNewText.prototype.allQuotes = [
aQuotes,
bQuotes,
cQuotes,
]
GenerateNewText.prototype.getRandomSentence = function() {
if ( !this.characterQuotes ) {
this.characterQuotes = this.allQuotes[ Math.floor(Math.random() * allQuotes.length) ]
}
return this.characterQuotes[ Math.floor(Math.random() * characterQuotes.length) ]
}
I'm trying to pull a random quote from an array. I need to display an initial quote and then get a new one, no same two quotes back to back. Here's what I got.
$(document).ready(function() {
var quoter = [{
quote: "I drink to make other people more interesting.",
author: "Ernest Hemingway"
}, {
quote: "Alcohol may be man's worst enemy, but the bible says love your enemy.",
author: "Frank Sinatra"
}, {
quote: "Reality is an illusion created by a lack of alcohol.",
author: "N.F. Simpson"
},{
quote: "Time is never wasted when you’re wasted all the time.",
author: "Catherine Zandonella"
},{
quote: "I feel bad for people who don’t drink. When they wake up in the morning, that’s as good as they’re going to feel all day.",
author: "Frank Sinatra"
}];
var randomQuote = Math.floor(Math.random() * quoter.length);
//$(function () {
//Set Original Quote
$('#quoteText').text(quoter[randomQuote].quote);
$('#authorText').text(quoter[randomQuote].author);
//});
$('#btnNew').click(function(evt) {
//prevent browser's default action
evt.preventDefault();
//getting a new random number to attach to a quote and setting a limit
var sourceLength = quoter.length;
var randomNumber = Math.floor(Math.random() * sourceLength);
//set a new quote
//while ( randomNumber <= sourceLength ) {
while (randomNumber === randomNumber){
var newQuoteText = quoter[randomNumber].quote;
var newQuoteGenius = quoter[randomNumber].author;
var timeAnimation = 500;
var quoteContainer = $('#quoteContainer');
//fade out animation with callback
quoteContainer.fadeOut(timeAnimation, function() {
//set text values
$('#quoteText').text(newQuoteText);
$('#authorText').text(newQuoteGenius);
//console.log(quoteText,authorText);
//fadein animation.
quoteContainer.fadeIn(timeAnimation);
});
break;
}; //end while loop
}); //end btnNew function
}); //end document ready
I need to do this by using a while loop. I can't figure out how to store the random quote (array value) and then compare it to the new random one to get a different random on if it's the same.
The HTML is here:
<div id="quoteContainer">
<p><span id="quoteText"></span><Br/></p>
—<span id="authorText"> </span>
</div>
You can have a simple variable store the previous value, then check to see if the random number is the same as the last time.
$(document).ready(function(){
//....your current above code
var lastQuote = randomQuote;
$(button).click(function(){
var thisQuote = Math.floor(Math.random() * sourceLength);
//This will only be entered if the two are equal
//The while loop ensures that if you get a new random number
//it won't be the same
while(thisQuote == lastQuote){
thisQuote = Math.floor(Math.random() * sourceLength);
}
//If you make it here a unique number has been found
lastQuote = thisQuote;
});
});
Your approach might result in an infinite loop. Won't happen, because the random-number generator is not perfect but it can be done easier:
Either shuffel the array and go down linearly (or construct a fancy generator if you want) or just delete every quote that has been shown already.
I'm creating a random quote generator that is supposed to give you a random quote along with the person who said it, but I've created two separate arrays because it'll make it easier to edit the visual aspects of the page later on. The first array has the quote itself and the second array has the names of the people who said them. I would like to generate one random number and then use that as my index on both arrays, thus getting a random quote and the corresponding person who said it.
The first thing I tried was this:
var randomIndex = function() {
return Math.floor(Math.random() * quotes.length);
};
button.addEventListener("click", function(){
quoteBox.textContent = '"' + quotes[randomIndex()] + people[randomIndex()] + '"';
});
But that gives me two different random numbers (because I'm calling the function twice, I suppose). I then tried setting the random number to a variable and using that as the index, but that doesn't change unless I refresh the page and I want it to change on the click of a button. Is what I want to do possible?
Try calling randomIndex inside your click handler.
button.addEventListener("click", function(){
var random = randomIndex();
quoteBox.textContent = '"' + quotes[random] + people[random] + '"';
});
That will assign a new index each time the click handler runs, but will use the same index to access both quotes and people.
Instead of having 2 arrays for quotes and people, use a unique array of objects, each one having 2 members quote and people.
var quotes = [
{quote: 'The quote text', author: 'Its author'},
{quote: 'A second quote text', author: 'The 2nd author'},
// ...
];
button.addEventListener("click", function(){
var quote = quotes[randomIndex()];
quoteBox.textContent = '"' + quote.quote + quote.index + '"';
});
Try this :)
var randomIndex = function() {
return Math.floor(Math.random() * quotes.length);
};
button.addEventListener("click", function(){
var index = randomIndex();
quoteBox.textContent = '"' + quotes[index] + people[index] + '"';
});
I would suggest instead of maintaining two arrays use one that stores objects with key value pairs of what you need to use in the quote. see below.
var quotes = [{
quote: 'something something darkside',
person: 'family guy sith lord'
}, {
quote: 'something something evil',
person: 'family guy sith lord'
}, {
quote: 'blah blah blah',
person: 'foobar'
}];
var
quoteEl = document.querySelector('#quote'),
personEl = document.querySelector('#person'),
button = document.querySelector('#button');
button.addEventListener("click", getQuote);
getQuote();
function getQuote() {
var quote = quotes[randomIndex(quotes.length)];
quoteEl.innerHTML = quote.quote;
personEl.innerHTML = quote.person;
}
function randomIndex(max) {
return Math.floor(Math.random() * max);
};
blockquote {
padding: .5em;
margin: 1em;
background: #eee;
border-left: 1em solid #aaa;
color: rgba(37, 37, 37, .87);
}
#person {
text-decoration: none;
color: rgba(37, 37, 37, .87);
}
#person::before {
content: ' -- ';
}
#person:hover {
text-decoration: underline;
}
<blockquote>
<p id="quote"></p>
<footer>
</footer>
</blockquote>
<button id="button">get a random quote
</button>