'Javascript string array ordering (based on value order)
I am currently using a typewriter effect from Codepen and would like to order strings in the order in which they are listed (not random).
function getRandomPun() {
const puns = [
"String one",
"String two",
"String three"
];
const index = Math.floor(Math.random() * puns.length);
return puns[index];
}
startType(getRandomPun(), 0);
I have tried replacing the index with Math.floor(Math.round(puns.length) but it has no effect.
function getThePun() {
const puns = [
"String one",
"String two",
"String three"
];
const index = Math.floor(Math.round(puns.length);
return puns[index];
}
startType(getThePun(), 0);
I also tried the following but only the first string it outputted:
function getThePun() {
const puns = [
"String one",
"String two",
"String three"
];
return puns[0];
}
startType(getThePun(), 0);
Any help or tips would be greatly appreciated.
Solution 1:[1]
Not sure what the usecase is here, but here is how to sort
const puns = [
"String shortest",
"String - the longest",
"String three long"
];
function getRandomPun(len) {
if (len) puns.sort((a,b) => a.length - b.length)
console.log(puns)
const index = Math.floor(Math.random() * puns.length);
return puns[index];
}
console.log(getRandomPun());
console.log(getRandomPun(true));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mplungjan |
