How to make JavaScript Bingo generator not repeat same result? - javascript

I am trying to make a Thanksgiving Bingo generator and want to make it so the phrases appear only once.
Not sure what direction to take. Here is the code so far:
var questions = [
"Can name all 3 Pilgrim ships",
"Plays football",
"Has an unusual Thanksgiving tradition",
"Has a turkey disaster story",
"Vegetarian",
"Loves cranberry sauce",
"Has celebrated Thanksgiving in another country",
"Can name 5 things grateful for",
"Makes a mean green bean casserole",
"Eats mac and cheese on Thanksgiving",
"Has worked retail on Black Friday",
"Thanksgiving is favorite holiday",
"Has seen a turkey in real life",
"Watched the Macy's T-day parade in person",
"Willing to share pie recipe",
"Has attended a Friendsgiving",
"Loves leftovers",
"Dines out for Thanksgiving",
"Can name 5 native American tribes",
"Watches football",
"Can gobble like a turkey",
"Celebrates Canadian Thanksgiving",
"Hates cranberry sauce",
"Goes Black Friday shopping"
]
function newQuestion() {
var randomNumber = Math.floor(Math.random() * (questions.length));
document.getElementById('question-display').innerHTML = questions[randomNumber];
}

I think Shuffle and pop like #epascarello commented out is the perfect way in this case, here is an example:
var questions = [
"Can name all 3 Pilgrim ships",
"Plays football",
"Has an unusual Thanksgiving tradition",
"Has a turkey disaster story",
"Vegetarian",
"Loves cranberry sauce",
"Has celebrated Thanksgiving in another country",
"Can name 5 things grateful for",
"Makes a mean green bean casserole",
"Eats mac and cheese on Thanksgiving",
"Has worked retail on Black Friday",
"Thanksgiving is favorite holiday",
"Has seen a turkey in real life",
"Watched the Macy's T-day parade in person",
"Willing to share pie recipe",
"Has attended a Friendsgiving",
"Loves leftovers",
"Dines out for Thanksgiving",
"Can name 5 native American tribes",
"Watches football",
"Can gobble like a turkey",
"Celebrates Canadian Thanksgiving",
"Hates cranberry sauce",
"Goes Black Friday shopping"
].sort(_=> Math.random() - 0.5);
document.querySelector("#get-question").onclick = function() {
document.getElementById('question-display').innerHTML = questions.pop() || "There are no more questions!";
}
<p id="question-display"></p>
<button id="get-question">Get new question</button>

Related

How can I generate a random selection based on user's <select> option choice?

I am trying to have a user select a genre from my drop down list and get a random result from the genre they selected that is then displayed on the screen.
In other words, my idea is to have a user get a random options from the genre they choose from my list.
I am very very new to JavaScript but I want to try to do something creative for my project. I have tried this so far
function xyz() {
var x = document.getElementById("selectedId").value;
if (x == "action") {
var action = ["Attack on Titan", "Fullmetal Alchimist", "One Punch Man", "Sword Art Online", "My Hero Academia", "Demond Slayer", "Naruto", "Tokyo Ghoul", "Hunter x Hunter", "Code Geass", "Jujutsu Kaisen", "One Piece", "Noragami", "Akame ga Kill!", "Mob Psycho 100", "Assassination Classroom", "Blue Exorcist", "Bleach", "Parastyle", "Cowboy Bebop", "Fairy Tail", "Soul Eater", "Jojo's Bizarre Adventure", "Black Clover", "Fullmetal Alchemist", "That Time I got Reincarnated as a Slime", "Fire Force", "Balck butler", "Spy x Family", "The Seven Deadly Sins", "Tokyo Revengers", "Devilman: Crybaby", "Chainsaw Man"]
var result = Math.floor(Math.random() * action.length);
console.log(action);
} else if (x == "comedy ") {
var comedy = ["One Punch Man", "No Game NO Life", "Mob Psycho 100", "Assassination Classroom", "KonoSuba: God's Blessing on This Wonderful World!", "Kill la Kill", "Rascal Does Not Dream of Bunny Girl Senpai", "Dr.Stone", "Kaguya-sama: Love is War", "Soul Eater", "Gurren Lagann", "The Devil is a Part-Timer", "Black Clover", "High School DxD", "That Time I Got Reincarnated as a Slime", "Maid Sama!", "Spy x Family", "Black Butler", "Nisekoi", "Ouran High School Host Club", "My Little Monster", "JoJo's Bizarre Adventure:", "K-On!", "The Disastrous Life of Saiki K.", "My Teen Romantic Comedy SNAFU TOO!", "Golden Time", "Monthly Girls' Nozaki-kun", "Rent-a-Girlfriend", "The Quintessential Quintuplets", "Don't Toy with Me, Miss Nagatoro", "How Not to Summon a Demon Lord", "Ghost Stories"]
var result = Math.floor(Math.random() * comedy.length);
console.log(comedy);
} else if (x == "drama") {
var drama = ["Attack on Titan", "Fullmetal Alchemist", "Your Name.", "Steins:Gate", "A Silent Voice", "Code Geass", "Toradora!", "Your Lie in Apirl", "Re:Zero", "Angel Beats!", "Death Parade", "Violet Evergarden", "Rascal Does Not Dream of Bunny Girl Senpai", "Anohana: The Flower We Saw That Day", "Clannad", "Charlotte", "Kakegurui", "Made in Abyss", "The Pet Girl of Sakurasou", "Guilty Crown", "Jojo's Bizarren Adventure", "Classroom of the Elite", "Tokyo Revengers", "ReLIFE", "Monster", "5 Centimeters Per Second", "Plasic Memories", "Tower of God", "The Garden of Words", "Banana Fish", "Orange", "To Your Eternity", "Fruits Basket", "91 Days"]
var result = Math.floor(Math.random() * drama.length);
console.log(drama);
} else if (x == "sliceofLife") {
var sliceofLife = ["Violet Evergarden", "Anohana: The Flower We Saw That Day", "Hyouka", "Miss Kobayashi's Dragon Maid", "ReLIFE", "5 Centimeters Per Second", "The Melancholy of Haruhi Suzumiya", "Blue Spring Ride", "Kimi ni Todoke: From Me to You", "I Want To Eat Your Pancreas", "My Dress-Up Darling", "The Garden of Words", "Beastars", "Mushu-Shi", "Wolf Children", "Nana", "Barakamon", "Natsume's Book of Friends", "Bunny Drop", "Laid-Back Camp", "Love-Live!", "Tanaka-Kun is Always Listless", "Kimi ni Todoke", "School-Live!", "Tamako Market", "Beck", "Place to Place", "One Week Friends", "Girls' Last Tour", "Remake Our Life!", "Silver Spoon", "Flying Witch", "Doukyusei-Classmates", "Colorful"]
var result = Math.floor(Math.random() * sliceofLife.length);
console.log(sliceofLife);
} else if (x == "fantasy") {
var fantasy = ["Sword Art Online", "Demon Slayer", "Naruto", "Tokyo Ghoul", "Hunter x Hunter", "No Game No Life", "Jujutsu Kaisen", "One Piece", "Noragami", "Re:Zero", "Akame ga Kill!", "The Seven Deadly Sins", "Bleach", "Blue Exorcist", "Fairy Tale", "Violet Evergrden", "Soul Eater", "The Devil is a Part-Timer!", "Black Clover", "Overlord", "The Rising of the Shield Hero", "Is it Wrong to Try to Pick Up Girls in a Dungeon", "fate/Zero", "Noragami Aragoto", "Demond Slayer", "That Time I Got Reincarnated as a Slime", "log Horizon", "Re:Zero", "Goblin Slayer", "Tenki no Ko", "Tower of God", "The God of High School", "GATE", "Fruits Basket", "The Asterisk War"]
var result = Math.floor(Math.random() * fantasy.length);
console.log(fantasy);
} else if (x == "horror") {
var horror = ["Tokyo Ghoul", "Parasyte", "Another", "Elfen Lied", "Highschool of the Dead", "Deadman Wonderland", "Devilman: Crybaby", "Hellsling Ultimate", "Akira", "When They Cry", "Kabaneri of the Iron Fortress", "From the New World", "Beserk", "Shiki", "Ajin", "Psprika", "Dorohedoro", "Mieruko-chan", "Blood+", "Corpse Party: Tortured Souls", "Hell Girl", "Gantz", "Danganronpa", "Mononoke", "High-Rise Invasion", "Happy Sugar Life", "Ghost Hunt", "The Los Village", "Pupa", "Ghost Stories", "Lunar Ledgen Tsukihime", "Junji Ito Collection", "Zetman", "Memories"]
var result = Math.floor(Math.random() * horror.length);
console.log(horror);
} else if (x == "mystery") {
var mystery = ["Earsed", "The Promised Neverland", "Another", "Kakegutui", "Durarara", "Hyouka", "Made in Abyss", "Bungo Stray Dog", "Black Butler", "Monster", "Darker then Black", "Black Bullet", "Tower of God", "When They Cry", "K", "From the New World", "Serial Experiments Lain", "Great Pretender", "Vanpire Knight", "Eden of The East", "No.6", "Summer Time Rendering", "Wolf's Rain", "Amnesia", "High-Rise Invation", "Astra Lost in Space"]
var result = Math.floor(Math.random() * mystery.length);
console.log(mystery);
} else if (x == "psychological") {
var psychological = ["Deaht Note", "Tokyo Ghoul", "Re:Zero", "Erased", "The Future Diary", "The Promised Neverland", "Psycho-Pass", "Terror in Resonance", "Classroom of the Elite", "Btooom!", "FLCL", "Perfect Blue", "Ergo Proxy", "The Fruit of Grisaia", "Shiki", "Blast of Tempest", "Paranoia Agent", "Cyberpunk: Edgerunners", "Moriarty the Patriot", "Platinum Emd", "B: The Beginning", "Invaded", "When Marnie Was There", "Tomodachi Game", "Haibane Renmei", "Death Billards", "Flowers of Evil"];
var result = Math.floor(Math.random() * psychological.length);
console.log(psychological);
} else {
var boysLove = ["Given", "No.6", "Love Stage!", "Beyond the Boundary: I'll Be Here - Future", "Junjou Romantica", "Doukyusei -Classmates-", "Hitorijimd My Hero", "Sasaki and Miyano", "Dakaretai Otoko 1-i ni Odosarete Imasu.", "Super Lovers", "Yarchin Bitch-bu", "Gakuen Heaven", "kirepapa", "Yes, No, or Maybe?", "Ten Count", "Fake"]
var result = Math.floor(Math.random() * boysLove.length);
console.log(boysLove);
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<!--Language encoding-->
<meta name="viewport" content="width=device-width, initial-scale=1.0>" <title> Final Project
</title>
<link rel="stylesheet" type="text/css" href="FPCSS.css" />
</head>
<body class="style">
<div id="Top">
<p class="title"> Anime for All
<IMG class="IMG1" SRC="five.gif"> </p>
<p>
<br>
</p>
<div class="Directory">
<!-- Website navigation-->
<h1>Directory</h1>
<p> Homepage</p>
<p> Anime History</p>
<p> Misconceptions and Genres</p>
<p> Recommendations</p>
<p> Random Anime Generator</p>
<p>Email me!</p>
</div>
<div class="MS">
<!--MS= format for main section-->
<h1>Random Anime Generator</h1>
<label> Select your Favorite genres to generate a anime!</label>
<select id="selectedId">
<option>Choose a Genre</option>
<option value="action"> Action</option>
<option value="adventure">Adventure</option>
<option value="comedy">Comedy</option>
<option value="drama">Drama</option>
<option value="sliceOfLife">Slice Of Life</option>
<option value="fantsy">Fantsy</option>
<option value="horror">Horror</option>
<option value="mystery">Mystery</option>
<option value="psychological">Psychological</option>
</select>
<p> Your random anime based on chosen genre is....</p>
<p id="result"> </p>
<script src="Final_Project_JS.js"></script>
</div>
</div>
You could store all full list of anime titles in a variable—preferably an object of arrays. Whenever user selects a genre, you could simply generate a random integer per each sublist's length and show the result in the target p element.
See the snippet below for working example. I didn't modify the original HTML markup too much, except removing irrelevant elements to the question.
For this to work as intended, you need to make sure the list of option values match the keys of titles object.
const titles = {
action: ["Attack on Titan", "Fullmetal Alchimist", "One Punch Man", "Sword Art Online", "My Hero Academia", "Demond Slayer", "Naruto", "Tokyo Ghoul", "Hunter x Hunter", "Code Geass", "Jujutsu Kaisen", "One Piece", "Noragami", "Akame ga Kill!", "Mob Psycho 100", "Assassination Classroom", "Blue Exorcist", "Bleach", "Parastyle", "Cowboy Bebop", "Fairy Tail", "Soul Eater", "Jojo's Bizarre Adventure", "Black Clover", "Fullmetal Alchemist", "That Time I got Reincarnated as a Slime", "Fire Force", "Balck butler", "Spy x Family", "The Seven Deadly Sins", "Tokyo Revengers", "Devilman: Crybaby", "Chainsaw Man"],
comedy: ["One Punch Man", "No Game NO Life", "Mob Psycho 100", "Assassination Classroom", "KonoSuba: God's Blessing on This Wonderful World!", "Kill la Kill", "Rascal Does Not Dream of Bunny Girl Senpai", "Dr.Stone", "Kaguya-sama: Love is War", "Soul Eater", "Gurren Lagann", "The Devil is a Part-Timer", "Black Clover", "High School DxD", "That Time I Got Reincarnated as a Slime", "Maid Sama!", "Spy x Family", "Black Butler", "Nisekoi", "Ouran High School Host Club", "My Little Monster", "JoJo's Bizarre Adventure:", "K-On!", "The Disastrous Life of Saiki K.", "My Teen Romantic Comedy SNAFU TOO!", "Golden Time", "Monthly Girls' Nozaki-kun", "Rent-a-Girlfriend", "The Quintessential Quintuplets", "Don't Toy with Me, Miss Nagatoro", "How Not to Summon a Demon Lord", "Ghost Stories"],
drama: ["Attack on Titan", "Fullmetal Alchemist", "Your Name.", "Steins:Gate", "A Silent Voice", "Code Geass", "Toradora!", "Your Lie in Apirl", "Re:Zero", "Angel Beats!", "Death Parade", "Violet Evergarden", "Rascal Does Not Dream of Bunny Girl Senpai", "Anohana: The Flower We Saw That Day", "Clannad", "Charlotte", "Kakegurui", "Made in Abyss", "The Pet Girl of Sakurasou", "Guilty Crown", "Jojo's Bizarren Adventure", "Classroom of the Elite", "Tokyo Revengers", "ReLIFE", "Monster", "5 Centimeters Per Second", "Plasic Memories", "Tower of God", "The Garden of Words", "Banana Fish", "Orange", "To Your Eternity", "Fruits Basket", "91 Days"],
sliceOfLife: ["Violet Evergarden", "Anohana: The Flower We Saw That Day", "Hyouka", "Miss Kobayashi's Dragon Maid", "ReLIFE", "5 Centimeters Per Second", "The Melancholy of Haruhi Suzumiya", "Blue Spring Ride", "Kimi ni Todoke: From Me to You", "I Want To Eat Your Pancreas", "My Dress-Up Darling", "The Garden of Words", "Beastars", "Mushu-Shi", "Wolf Children", "Nana", "Barakamon", "Natsume's Book of Friends", "Bunny Drop", "Laid-Back Camp", "Love-Live!", "Tanaka-Kun is Always Listless", "Kimi ni Todoke", "School-Live!", "Tamako Market", "Beck", "Place to Place", "One Week Friends", "Girls' Last Tour", "Remake Our Life!", "Silver Spoon", "Flying Witch", "Doukyusei-Classmates", "Colorful"],
fantasy: ["Sword Art Online", "Demon Slayer", "Naruto", "Tokyo Ghoul", "Hunter x Hunter", "No Game No Life", "Jujutsu Kaisen", "One Piece", "Noragami", "Re:Zero", "Akame ga Kill!", "The Seven Deadly Sins", "Bleach", "Blue Exorcist", "Fairy Tale", "Violet Evergrden", "Soul Eater", "The Devil is a Part-Timer!", "Black Clover", "Overlord", "The Rising of the Shield Hero", "Is it Wrong to Try to Pick Up Girls in a Dungeon", "fate/Zero", "Noragami Aragoto", "Demond Slayer", "That Time I Got Reincarnated as a Slime", "log Horizon", "Re:Zero", "Goblin Slayer", "Tenki no Ko", "Tower of God", "The God of High School", "GATE", "Fruits Basket", "The Asterisk War"],
horror: ["Tokyo Ghoul", "Parasyte", "Another", "Elfen Lied", "Highschool of the Dead", "Deadman Wonderland", "Devilman: Crybaby", "Hellsling Ultimate", "Akira", "When They Cry", "Kabaneri of the Iron Fortress", "From the New World", "Beserk", "Shiki", "Ajin", "Psprika", "Dorohedoro", "Mieruko-chan", "Blood+", "Corpse Party: Tortured Souls", "Hell Girl", "Gantz", "Danganronpa", "Mononoke", "High-Rise Invasion", "Happy Sugar Life", "Ghost Hunt", "The Los Village", "Pupa", "Ghost Stories", "Lunar Ledgen Tsukihime", "Junji Ito Collection", "Zetman", "Memories"],
mystery: ["Earsed", "The Promised Neverland", "Another", "Kakegutui", "Durarara", "Hyouka", "Made in Abyss", "Bungo Stray Dog", "Black Butler", "Monster", "Darker then Black", "Black Bullet", "Tower of God", "When They Cry", "K", "From the New World", "Serial Experiments Lain", "Great Pretender", "Vanpire Knight", "Eden of The East", "No.6", "Summer Time Rendering", "Wolf's Rain", "Amnesia", "High-Rise Invation", "Astra Lost in Space"],
psychological: ["Deaht Note", "Tokyo Ghoul", "Re:Zero", "Erased", "The Future Diary", "The Promised Neverland", "Psycho-Pass", "Terror in Resonance", "Classroom of the Elite", "Btooom!", "FLCL", "Perfect Blue", "Ergo Proxy", "The Fruit of Grisaia", "Shiki", "Blast of Tempest", "Paranoia Agent", "Cyberpunk: Edgerunners", "Moriarty the Patriot", "Platinum Emd", "B: The Beginning", "Invaded", "When Marnie Was There", "Tomodachi Game", "Haibane Renmei", "Death Billards", "Flowers of Evil"],
boysLove: ["Given", "No.6", "Love Stage!", "Beyond the Boundary: I'll Be Here - Future", "Junjou Romantica", "Doukyusei -Classmates-", "Hitorijimd My Hero", "Sasaki and Miyano", "Dakaretai Otoko 1-i ni Odosarete Imasu.", "Super Lovers", "Yarchin Bitch-bu", "Gakuen Heaven", "kirepapa", "Yes, No, or Maybe?", "Ten Count", "Fake"]
}
const selectionHandler = e => {
const genre = e.target.value;
const targetList = titles[genre];
if (!targetList) {
result.innerText = "No anime found";
} else {
const randomIndex = Math.floor(Math.random() * targetList.length);
result.innerText = targetList[randomIndex];
}
}
const input = document.querySelector('#selectedId');
const result = document.querySelector('#result');
input.addEventListener('change', selectionHandler);
#result {
padding: 10px;
background: #eee;
display: inline-block;
}
<div id="Top">
<p class="title"> Anime for All</p>
<div class="MS">
<!--MS= format for main section-->
<h1>Random Anime Generator</h1>
<label> Select your Favorite genres to generate a anime!</label>
<select id="selectedId">
<option>Choose a Genre</option>
<option value="action"> Action</option>
<option value="adventure">Adventure</option>
<option value="comedy">Comedy</option>
<option value="drama">Drama</option>
<option value="sliceOfLife">Slice Of Life</option>
<option value="fantasy">Fantsy</option>
<option value="horror">Horror</option>
<option value="mystery">Mystery</option>
<option value="psychological">Psychological</option>
</select>
<p> Your random anime based on chosen genre is....</p>
<p id="result"></p>
</div>
</div>

How to implement a 'contains' search in JavaScript

I'm creating a search box that allows you to search for different companies. I'd like the search box to perform a 'contains' search. For example, let's say that I want to look up the company ExxonMobil Oil Corp. Typing in any of the following should include the company in the list of results (this isn't exhaustive):
oil
corp
oil corp
exxonmobil
exxonmobil oil
exxonmobil oil corp
The words don't have to be complete, just to be clear. The phrase 'oil co', for instance, should still bring up a result.
Typing in 'exxonmobil corp', however, will not bring up the company as a result since 'corp' does not immediately follow 'exxonmobil' in the company's name.
Is there a go-to method for implementing this type of search, keeping time efficiency in mind? In my case, there can be thousands of companies to search through. And I'd like to be able to display the list of results on the fly as the user is typing into the search box.
I'm aware of the trie data structure, but from what I've read, it seems to work best for 'starts with' searches. So it wouldn't match searches like 'oil corp', 'oil', or 'corp' with ExxonMobil Oil Corp. Perhaps there's a way to tweak the trie to do as I want, but I'm just not sure if that's the best way to go.
Thank you for the responses. A few of you suggested looking into String.prototype.includes(). I gave that a try, and it does seem to work well with no performance issues.
100 companies is fast.
const companies = [
"Arcade Flower Shop",
"Madam Malkin's Robes for All Occasions",
"Victoria's Circuit",
"33¢ Store",
"El Banco Corrupto",
"Silver Shamrock",
"Stay Puft Corporation",
"Wonka Industries",
"Blue Moon Detective Agency",
"The Foundation",
"Macmillan Toys",
"The Reef",
"Merrick BioTech",
"The Peach Pit",
"The Korova Milkbar",
"Paper Street Soap Company",
"Mel's Diner",
"Dunder Miflin",
"The Everything Store",
"Rodbell's",
"Rex Kwan Do",
"The Fairly Oddparents",
"Vitameatavegamin",
"Bushwood Country Club",
"Consumer Recreation Services",
"The Rusty Anchor",
"IPS (International Parcel Services)",
"Pendant Publishing",
"Lacuna Inc.",
"H.A.L. Labs",
"Life Extension",
"Rekall",
"Bluehound Bus Line",
"Atlantic American Airlines",
"KACL",
"Flingers",
"Burrito Explosion",
"Fatso's",
"The Max",
"McDowell's",
"Bada Bing",
"Wu-Tang Financial",
"Wally World",
"The Dharma Initiative",
"The Leftorium",
"Edna's Edibles",
"Daily Planet",
"21 Jump Street",
"The Enterprise",
"Powell Family",
"Central Perk",
"Night Court",
"Arnold's Drive-In",
"WKRP",
"Moe's Tavern",
"Lomax Industries",
"Hudsucker Industries",
"Los Pollos Hermanos",
"Chubby's",
"Mugatu Industries",
"The Daily Bugle",
"Globex Corporation",
"Entertainment 720",
"Soylent Corporation",
"SS Minnow",
"TGS with Tracy Jordan",
"Grace Adler Designs",
"Pierce & Pierce",
"Wayne Enterprises",
"Cheers",
"Goliath National Bank",
"Pricemart",
"Career Transitions Corporation",
"Bluth's Original Frozen Banana",
"Livingston",
"Luke's Diner",
"Adventureland",
"Buy-N-Large",
"Average Joe's Gym",
"Duff Beer",
"Michael Scott Paper Company",
"Brawndo",
"Fisher & Sons",
"Mitch and Murray",
"Multi National United",
"Oscorp",
"Pizza Planet",
"Momcorp",
"Ewing Oil",
"Prestige Worldwide",
"Tyrell Corporation",
"Omni Consumer Products",
"Monsters Inc.",
"Ghostbusters",
"Pied Piper",
"TelAmeriCorp",
"Yakonomo Corporation",
"Mega Lo Mart",
"Vandelay Industries",
"Frosty Palace",
"Sterling Cooper Draper Pryce",
"M.I.B.",
"The Smash Club"
];
const search = document.getElementById("search");
const output = document.getElementById("output");
const filter = (evt) => {
const val = evt.target.value;
if (val.length < 1) return output.value = "";
output.value = companies.filter(company => company.toLowerCase().includes(val.toLowerCase())).join("\n");
}
search.addEventListener("keyup", filter);
input,
textarea {
margin-top: 1em;
}
<link href="https://unpkg.com/marx-css/css/marx.min.css" rel="stylesheet" />
<main>
<input type="text" id="search" />
<textarea rows=4 id="output"></textarea>
</main>

How do I add an if and else statement so it gives me related movies when the current movie is loaded?

Here's my code.
I have a movies related tab and when a specific movie is open in a browser, under the related tab, related movies should be there. I have the map functions ready which load all the movies I have in the map object. Wanted an if and else statement to pick the same genre of movies by using a getElementId to get the id genre of the current movie and compare it with the genre in the map objects. Hope am using the right terms
//create test div
const data = [{
name: "13 reasons why",
href: "13 reasons why.php",
img: "https://images.theconversation.com/files/170594/original/file-20170523-5763-161mnda.jpg",
describe: "Newcomer Katherine Langford plays the role of Hannah, a young woman who takes her own life. Two weeks after her tragic death, a classmate named Clay finds a mysterious box on his porch. Inside the box are recordings made by Hannah -- on whom Clay had a crush -- in which she explains the 13 reasons why she chose to commit suicide. If Clay decides to listen to the recordings, he will find out if and how he made the list. This intricate and heart-wrenching tale is told through Clay and Hannah's dual narratives.",
rate: "7.6",
date: "(2017 - 2020)"
}, {
name: "30 Coins",
href: "30 coins.php",
img: "https://www.themoviedb.org/t/p/w500/b2i9aaV6ncULl9jYXEoPi7VFJg8.jpg",
describe: "Father Vergara, an exorcist, boxer and ex-convict exiled to a remote town in Spain, enlists the help of the mayor and a veterinarian when a series of paranormal phenomena begins to occur.",
rate: "7.2",
date: "(2020 - Present)"
}, {
name: "911 Lone Star",
href: "911 lone star.php",
img: "https://m.media-amazon.com/images/I/717AkBpHNjL._AC_SY450_.jpg",
describe: "9-1-1: Lone Star follows a sophisticated New York firefighter who, along with his son, relocates from Manhattan to Austin, Texas. He must try to balance the duties of saving those who are at their most vulnerable and solving the problems in his own life. ",
rate: "6.8",
date: "(2017 - 2021)"
}, {
name: "911",
href: "911.php",
img: "https://m.media-amazon.com/images/M/MV5BMzNiMmNmZWQtMTJlMS00NWIyLTlhNmEtNmI3M2Q1YjczMGI4XkEyXkFqcGdeQXVyNjEwNTM2Mzc#._V1_.jpg",
describe: "Policemen, paramedics and firefighters put themselves in dangerous situations to save people's lives. Meanwhile, they also have to deal with their personal problems.",
rate: "7.6",
date: "(2018 - Present)"
}, {
name: "A confession",
href: "a confession.php",
img: "https://m.media-amazon.com/images/M/MV5BZTc0ZjQxOWEtNTc4MS00ZjgxLThkOWEtZGM1NzgzOWYwOTc1XkEyXkFqcGdeQXVyMTAyNjU1NjU5._V1_.jpg",
describe: "The true story of DS Stephen Fulcher and his hunt for missing 22-year-old Sian O'Callaghan, and how it lead to the arrest of Christopher Halliwell. This was the beginning of the capture of a prolific serial killer and the detectives own downfall.",
rate: "7.6",
date: "(2019)"
}, {
name: "A million little things",
href: "a million little things.php",
img: "http://www.gstatic.com/tv/thumb/tvbanners/17114373/p17114373_b_v12_aa.jpg",
describe: "The lives of a group of carefree friends from Boston change when one of them shockingly dies. They soon realise the importance of cherishing their friendship.",
rate: "7.9",
date: "(2018)"
}, {
name: "A teacher",
href: "a teacher.php",
img: "https://m.media-amazon.com/images/M/MV5BZjgzMmUwZjgtNzNhMi00M2Y0LWIxOTAtYzYzODdjMTYzZWQyXkEyXkFqcGdeQXVyMTIwNDUyNzMy._V1_.jpg",
describe: "This drama series examines the complexities and consequences of an illicit sexual affair between a young teacher and her student. Claire is a new teacher at Westerbrook High School in Texas. Dissatisfied in her marriage to her college sweetheart, Claire's life changes when Eric, a personable teenager in her English class, takes an interest in her. Popular and outgoing, Eric is the captain of the soccer team and nearly inseparable from his best friends. Everything seems perfect on the surface, but Eric is forced to juggle the pressures of school, applying for college and a part-time job, all while helping take care of his two younger brothers. Claire and Eric discover an undeniable connection that allows them to escape their lives, but their relationship accelerates faster than either could anticipate. The permanent damage left in the wake of their illicit affair becomes impossible for them, and their friends and family, to ignore.",
rate: "6.9",
date: "(2020)"
}, {
name: "Absentia",
href: "absentia.php",
img: "https://m.media-amazon.com/images/M/MV5BNmFiNDI5ODUtODQ2ZC00ZjUwLWFhYjQtMjk3MmMzZjY1ZWU2XkEyXkFqcGdeQXVyMTkxNjUyNQ##._V1_.jpg",
describe: ">Six years after going missing and being declared dead, FBI agent Emily Byrne is found alive in a cabin in the woods. With no memory of her past, she sets out to reclaim her life and identity.",
rate: "7.3",
date: "(2017 - 2020)"
}, {
name: "After Life",
href: "after life.php",
img: "https://m.media-amazon.com/images/M/MV5BZjdjOWIxMDgtYTgwNS00MjE4LTliZWYtZGI1NDhhZmIyYjM1XkEyXkFqcGdeQXVyMTkxNjUyNQ##._V1_.jpg",
describe: "Tony had a perfect life -- until his wife Lisa died. After that tragic event, the formerly nice guy changed. After contemplating taking his life, Tony decides he would rather live long enough to punish the world by saying and doing whatever he likes. He thinks of it as a superpower -- not caring about himself or anybody else -- but it ends up being trickier than he envisioned when his friends and family try to save the nice guy that they used to know. Golden Globe winner Ricky Gervais stars in the comedy series, which he also writes and directs.",
rate: "8.4",
date: "(2019 - 2020)"
}, {
name: "Alex Rider",
href: "alex rider.php",
img: "https://m.media-amazon.com/images/M/MV5BOTg4ZmQ5ZjItZTllZC00NzUzLTkwMTEtMjIzYzliZjk2ODUwXkEyXkFqcGdeQXVyMTEyMjM2NDc2._V1_.jpg",
describe: "London teenager Alex Rider is recruited by the Department of Special Operations, a subdivision of the Secret Intelligence Service (MI6), to infiltrate a controversial corrective academy for the wayward offspring of the ultra-rich.",
rate: "7.6",
date: "(2020)"
}, {
name: "All Rise",
href: "all rise.php",
img: "https://m.media-amazon.com/images/M/MV5BYTk5ZjI0M2MtYjQ5Ny00OWJmLWExYWEtNjRlMTdkNjYwMGIzXkEyXkFqcGdeQXVyMTkxNjUyNQ##._V1_.jpg",
describe: "A look inside the chaotic, hopeful and sometimes absurd lives of judges, prosecutors and public defenders as they work with bailiffs, clerks and cops to get justice for the people of Los Angeles amidst a flawed legal process. Among them is newly appointed Judge Lola Carmichael, a highly regarded and impressive deputy district attorney who doesn't intend to sit back on the bench in her new role, but instead leans in, immediately pushing the boundaries and challenging the expectations of what a judge can be.",
rate: "6.7",
date: "(2019 - 2021)"
}, {
name: "Altered Carbon",
href: "altered carbon.php",
img: "https://m.media-amazon.com/images/M/MV5BNjIxMWMzMzctYmZkYy00OTkzLWFlMWUtMjc3ZDFmYzQ3YmVkXkEyXkFqcGdeQXVyNjU2ODM5MjU#._V1_.jpg",
describe: "More than 300 years in the future, society has been transformed by new technology, leading to human bodies being interchangeable and death no longer being permanent. Takeshi Kovacs is the only surviving soldier of a group of elite interstellar warriors who were defeated in an uprising against the new world order. His mind was imprisoned for centuries until impossibly wealthy businessman Laurens Bancroft offers him the chance to live again. Kovacs will have to do something for Bancroft, though, if he wants to be resurrected. Bancroft's request of Kovacs is to solve a murder Bancroft's. 'Altered Carbon' is based on Richard K. Morgan's cyberpunk noir novel of the same name.",
rate: "8",
date: "(2018 - 2020)"
}, {
name: "American Horror Story",
href: "american horror story.php",
img: "https://flxt.tmsimg.com/assets/p9423798_b_v12_ad.jpg",
describe: "An anthology series centering on different characters and locations, including a house with a murderous past, an insane asylum, a witch coven, a freak show circus, a haunted hotel, a possessed farmhouse, a cult, the apocalypse, a slasher summer camp, and a bleak beach town and desert valley.",
rate: "7.6",
date: "(2011 - Present)"
}, {
name: "Anne With An E",
href: "anne with an e.php",
img: "https://m.media-amazon.com/images/M/MV5BNThmMzJlNzgtYmY5ZC00MDllLThmZTMtNTRiMjQwNmY0NmRhXkEyXkFqcGdeQXVyMTkxNjUyNQ##._V1_FMjpg_UX1000_.jpg",
describe: "This reimagining of the classic book and film is a coming-of-age story about a young orphan who is seeking love, acceptance and her place in the world. Amybeth McNulty stars as Anne, a 13-year-old who has endured an abusive childhood in orphanages and the homes of strangers. In the late 1890s, Anne is mistakenly sent to live with aging siblings, Marilla and Matthew Cuthbert, who live on Prince Edward Island. Anne, who proves to be uniquely spirited, imaginative and smart, transforms the lives of Marilla, Matthew and everyone else in their small town.",
rate: "8.7",
date: "(2017 - 2019)"
}, {
name: "animal kingdom",
href: "animal kingdom.php",
genre: "drama",
img: "https://m.media-amazon.com/images/M/MV5BOTk1NjAwOTM1OV5BMl5BanBnXkFtZTgwMzUwODQ3NzM#._V1_FMjpg_UX1000_.jpg",
describe: "After the death of his mother, Joshua decides to live with his grandmother, who heads a criminal clan. His life takes a turn as he gets involved with his cousins and their criminal activities.",
rate: "8.2",
date: "(2016 - Present)"
}, {
name: "Arrow",
href: "arrow.php",
genre: "drama",
img: "https://m.media-amazon.com/images/M/MV5BMTI0NTMwMDgtYTMzZC00YmJhLTg4NzMtMTc1NjI4MWY4NmQ4XkEyXkFqcGdeQXVyNTY3MTYzOTA#._V1_.jpg",
describe: "After mastering the skill of archery on a deserted island, multi-millionaire playboy Oliver Queen returns to his city to take on the vigilante persona of Arrow to fight crime and corruption.",
rate: "7.5",
date: "(2012 - 2020)"
}, {
name: "Atypical",
href: "atypical.php",
img: "https://m.media-amazon.com/images/M/MV5BMjNjNThmYTUtMjY2Ni00OGE4LTgzOTItYTgzMDllNDM5NTI5XkEyXkFqcGdeQXVyNjEwNTM2Mzc#._V1_FMjpg_UX1000_.jpg",
describe: "This heartfelt comedy follows Sam, a teenager on the autism spectrum, who has decided he is ready for romance. In order to start dating -- and hopefully find love -- Sam will need to be more independent, which also sends his mother (Jennifer Jason Leigh) on her own life-changing path. She and the rest of Sam's family, including a scrappy sister and a father seeking a better understanding of his son, must adjust to change and explore what it means to be normal. The series is created and written by Robia Rashid and Academy Award-winning producer Seth Gordon.",
rate: "8.3",
date: "(2017 - 2021)"
}]
const createTest = (selector) => {
const test = document.querySelector(selector)
console.log(selector)
let html = ''
data.map(({
id,
name,
href,
img,
describe,
rate,
date
}, index) => {
html = `
${html}
<div class="movie-item-style-2">
<div id="product${index}" class="mv-item-infor">
<img src="${img}" alt="">
<h6 style="padding-top: 1em;">${name} <span>${date}</span></h6>
<p class="rate"><i class="ion-android-star"></i><span>${rate}</span> /10</p>
<p class="describe">${describe}</p>
</div>
</div>
`
})
test.innerHTML = html
}
createTest(".content")
<div id="moviesrelated" class="tab">
<div class="row">
<h3>Related Movies</h3>
<div class="test"></div>
<div class="topbar-filter">
<p>Found <span>12 movies</span> in total</p>
<label>Sort by:</label>
<select>
<option value="popularity">Popularity Descending</option>
<option value="popularity">Popularity Ascending</option>
<option value="rating">Rating Descending</option>
<option value="rating">Rating Ascending</option>
<option value="date">Release date Descending</option>
<option value="date">Release date Ascending</option>
</select>
</div>
<div class="content">
</div>
<div class="topbar-filter">
<label>Movies per page:</label>
<select>
<option value="range">5 Movies</option>
<option value="saab">10 Movies</option>
</select>
<div class="pagination2">
<span>Page 1 of 2:</span>
<a class="active" href="#">1</a>
2
<i class="ion-arrow-right-b"></i>
</div>
</div>
</div>
</div>

Rendering JSON array in React component

I am trying to display an array of strings coming from an API. But I am not able to iterate through that array. If I pass the whole array inside HTML tag then it is rendering as a string.
For example: <div>{data.list.ingredients}</div> is working and displaying as a string. If I try to console this data.list.ingredients[0] it is throwing an error:
Cannot find 0 of undefined
My array:
{
"_id": "5b5446df2c89ab3d0e8d5526",
"title": "Chicken with Mustard Cream Sauce",
"vegetarian": false,
"ingredients": [
"4 whole Boneless Skinless Chicken Breasts",
"2 Tablespoons Olive Oil",
"2 Tablespoons Butter",
"3 whole Garlic Cloves Minced",
"1 cup Brandy",
"1 Tablespoon (heaping) Dijon Mustard",
"1 Tablespoon (heaping) Grainy Mustard",
"1/4 cup (to 1/2) Heavy Cream",
"1/4 cup (to 1/2) Chicken Broth",
"Salt And Pepper"
],
"image_url": "http://static.food2fork.com/chickenmustarde587.jpg",
"steps": [
"Amount of cream and broth has slightly decreased add more as needed",
"Cut the chicken breasts in half lengthwise so that you have eight smaller thinner chicken cutlets Salt and pepper both sides",
"Heat oil and butter in a large skillet over mediumhigh heat Cook cutlets on both sides until nice and golden brown and cooked through Remove chicken from the skillet and keep on a plate",
"Reduce the heat to medium Add the garlic to the pan and saute it for a minute stirring to make sure it wont burn Next pour in the brandy or wine if using being careful if cooking over an open flame Then just let the booze bubble up and cook until its reduced by half",
"Throw in the mustards and stir to combine then pour in the cream Stir in chicken broth adding more if the sauce seems too thick Taste sauce and adjust whatever you think it needs Add chicken breasts back to the pan nestling them into the sauce Allow sauce to cook for another few minutes shaking the pan if needed to move things around",
"Serve chicken with a green salad spooning the sauce over the top"
],
"serving": 5,
"cooking_time": 20
}
function renderData(){
let array = ['a','b','c','d' ];
return array.map((item, index) => <div key={index}>{ item }</div>);
}
I am assuming you are using axios (API component) so in your case you can get the result as follows:
axios.get('/youringredients.json')
.then(res => {
const ingredient = res.data.list.ingredients[0];
console.log(ingredient);
});
you can use ingredient in your state also.

Javascript object property not multiline

I am using a object in Javascript to store recipes and cannot get the "process" property to show as multiline. This has to be easy but not working. I am rendering the data as a tag in react.js.
let recipes = [
{
id:1,
dish: "Chicken and Rice",
ingredients: "Left over chicken",
process: "1)Chop up chicken in bite sized chunks\n 2)Heat 1 Tablespoon olive oil in your favorite pan\n3) Dice any veggies in your pantry and add these and chicken to pan and heat through.\n optional: Mix with fresh rice or quinoa to make more filling."
},
{
id:2,
dish: "Beef and Rice",
ingredients: "Left over beef",
process: "1)Chop up chicken in bite sized chunks <br> 2)Heat 1 Tablespoon olive oil in your favorite pan 3) Dice any veggies in your pantry and add these and chicken to pan and heat through optional: Mix with fresh rice or quinoa to make more filling."
},
{
id:3,
dish: "Rice and Rice",
ingredients: "Left over beef",
}
]
export default recipes;
You can split up the string on \n and map each line to an element.
render: function() {
let process = "1)Chop up chicken in bite sized chunks\n 2)Heat 1 Tablespoon olive oil in your favorite pan\n3) Dice any veggies in your pantry and add these and chicken to pan and heat through.\n optional: Mix with fresh rice or quinoa to make more filling.";
let lines = process.split("\n");
let mappedLines = lines.map((line)=>{
return <p>{line}</p>
});
return <div>{mappedLines}</div>;
}
https://jsfiddle.net/69z2wepo/82459/

Categories

Resources