Javascript Search Nested Object with Regex - javascript

I have this:
var foo = {
"Category1": [
{"Company1": {"URL": ["DomainName1", "DomainName2"]}},
...
],
...
}
Normally, I would access the DomainName1 like this:
foo["Category1"][0]["Company1"]["URL"][0]
However, I want to search all of foo for a certain DomainName, and I don't know any other information. I know that I could use several nested for loops, but that is very, very slow. What is an efficient way to do this? I was thinking of something along the lines of a '*' in place of ["Category1"], [0], etc. but I don't know how to do that.
Any help would be greatly appreciated.

My answer may be opinionated however still... With tens of thousands objects you're trying to re-invent the wheel. This is an exact candidate for a database storage. Either SQL or non-SQL like MongoDB.

This is a good problem to solve it using Jsonpath.
For instance, you can use this expression to look for all URL:
var out = jsonPath(json, "$..URL[*]").toJSONString() + "\n";
document.write(out);
You can use an expression to match the domain you want.
For your case, you can use this expression:
$..URL[?(#.indexOf('DomainName1') != -1)]
Jsonpath online tool
Here is a useful Jsonpath example from the documentation:
<html>
<head>
<title> JSONPath - Example (js)</title>
<script type="text/javascript" src="json.js"></script>
<script type="text/javascript" src="jsonpath.js"></script>
</head>
<body>
<pre>
<script type="text/javascript">
var json =
{ "store": {
"book": [
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{ "category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{ "category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
},
out = "";
out += jsonPath(json, "$.store.book[*].author").toJSONString() + "\n>";
out += jsonPath(json, "$..author").toJSONString() + "\n";
out += jsonPath(json, "$.store.*").toJSONString() + "\n";
out += jsonPath(json, "$.store..price").toJSONString() + "\n";
out += jsonPath(json, "$..book[(#.length-1)]").toJSONString() + "\n";
out += jsonPath(json, "$..book[-1:]").toJSONString() + "\n";
out += jsonPath(json, "$..book[0,1]").toJSONString() + "\n";
out += jsonPath(json, "$..book[:2]").toJSONString() + "\n";
out += jsonPath(json, "$..book[?(#.isbn)]").toJSONString() + "\n";
out += jsonPath(json, "$..book[?(#.price<10)]").toJSONString() + "\n";
out += jsonPath(json, "$..*").toJSONString() + "\n";
document.write(out);
</script>
</pre>
</body>
</html>
Example output:
["Nigel Rees","Evelyn Waugh","Herman Melville","J. R. R. Tolkien"]
["Nigel Rees","Evelyn Waugh","Herman Melville","J. R. R. Tolkien"]
[[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":12.99},{"category":"fiction","author":"Herman Melville","title":"Moby Dick","isbn":"0-553-21311-3","price":8.99},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}],{"color":"red","price":19.95}]
[8.95,12.99,8.99,22.99,19.95]
[{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}]
[{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}]
[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":12.99}]
[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":12.99}]
[{"category":"fiction","author":"Herman Melville","title":"Moby Dick","isbn":"0-553-21311-3","price":8.99},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}]
[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95},{"category":"fiction","author":"Herman Melville","title":"Moby Dick","isbn":"0-553-21311-3","price":8.99}]
[{"book":[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":12.99},{"category":"fiction","author":"Herman Melville","title":"Moby Dick","isbn":"0-553-21311-3","price":8.99},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}],"bicycle":{"color":"red","price":19.95}},[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":12.99},{"category":"fiction","author":"Herman Melville","title":"Moby Dick","isbn":"0-553-21311-3","price":8.99},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}],{"color":"red","price":19.95},{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":12.99},{"category":"fiction","author":"Herman Melville","title":"Moby Dick","isbn":"0-553-21311-3","price":8.99},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99},"reference","Nigel Rees","Sayings of the Century",8.95,"fiction","Evelyn Waugh","Sword of Honour",12.99,"fiction","Herman Melville","Moby Dick","0-553-21311-3",8.99,"fiction","J. R. R. Tolkien","The Lord of the Rings","0-395-19395-8",22.99,"red",19.95]
Just use the expression you want to easily query your json structure.

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>

Check if a array is contained in another

Im struggling with a piece of code i have below and cant seam to find something like it anywhere on stacks.
I have tried using the JavaScript .indexof(is returning all that doesn't contain variables) as well as the .match(shows all even if contain part of the word. i need it to be exact for obvious reasons) and even jquery.
I was wondering if anyone can help me.
I have a script that pulls data from the server into the following array.
from there i need to be able to compare this array with data that is on the page. if it exists in the server i want to highlight the checkbox i have created. when i did .match it found all variables that contained say the characters foo but i need exact matches not just if it contains.
see below for what i currently have. (note that the variables aren't set in stone and some may be different that will be contained in others which is why they need to be exact)
var industriesget = [ "Servers & Software", "Environmental Issues", "Hotels & Tourism"];
var industries = [ "Servers & Software", "Environmental Issues", "Hotels & Tourism", "Liquor, Wine & Beer", "Defense Industries", "Publishing & Printing", "Real Estate", "Not For Profit", "Food Services", "Corporate & Banking", "Agriculture & Fishing", "Communications", "Manufacturing", "Mining", "Entertainment & Gambling", "Retail Sales", "Signage & Fitouts", "Construction", "Transportation", "Public Utilities", "Education" ];
for ( var i = 0; i < industries.length; i++ ) {
//another for loop to run through the matches?
if..........
document.write( "<label for='" + industries[ i ] + "' class='col-md-2 col-xs-5' style=' float:left; height:55px;' valign='middle'>" + industries[ i ] + "<input valign='middle' type='checkbox' style='vertical-align: middle;text-align: center;' name='products' id='" + industries[ i ] + "' checked></label>" );
else{
document.write( "<label for='" + industries[ i ] + "' class='col-md-2 col-xs-5' style=' float:left; height:55px;' valign='middle'>" + industries[ i ] + "<input valign='middle' type='checkbox' style='vertical-align: middle;text-
}
}
Is this what you are looking for? This is simplest way.
var industriesget = [ "Servers & Software", "Environmental Issues", "Hotels & Tourism"];
var industries = [ "Servers & Software", "Environmental Issues", "Hotels & Tourism", "Liquor, Wine & Beer", "Defense Industries", "Publishing & Printing", "Real Estate", "Not For Profit", "Food Services", "Corporate & Banking", "Agriculture & Fishing", "Communications", "Manufacturing", "Mining", "Entertainment & Gambling", "Retail Sales", "Signage & Fitouts", "Construction", "Transportation", "Public Utilities", "Education" ];
for ( var i = 0; i < industries.length; i++ ) {
//another for loop to run through the matches?
if(industriesget.indexOf(industries[i])!== -1)
document.write( "<label for='" + industries[ i ] + "' class='col-md-2 col-xs-5' style=' float:left; height:55px;' valign='middle'>" + industries[ i ] + "<input valign='middle' type='checkbox' style='vertical-align: middle;text-align: center;' name='products' id='" + industries[ i ] + "' checked></label>" );
else{
document.write( "<label for='" + industries[ i ] + "' class='col-md-2 col-xs-5' style=' float:left; height:55px;' valign='middle'>" + industries[ i ] + "<input valign='middle' type='checkbox' style='vertical-align: middle;text-")
}
}
If you want to find whether industriesget is subset of industries, then try using
var intersectionIndustries = industries.filter(function(n) {
return industriesget.indexOf(n) !== -1;
});
and check
(intersectionIndustries.length == industriesget.length)
,if true then its subset, else there are non existent entries in industries get.
Use this:
pass two arrays to this function and check if the flag is true or not:
var industriesget = [ "Servers & Software", "Environmental
Issues", "Hotels & Tourism"];
var industries = [ "Servers & Software", "Environmental Issues", "Hotels
& Tourism", "Liquor, Wine & Beer", "Defense Industries", "Publishing &
Printing", "Real Estate", "Not For Profit", "Food Services", "Corporate &
Banking", "Agriculture & Fishing", "Communications", "Manufacturing",
"Mining", "Entertainment & Gambling", "Retail Sales", "Signage &
Fitouts",
"Construction", "Transportation", "Public Utilities", "Education" ];
if(arr(industriesget,industries)) {
alert("contains");
}
Where our function is:
function arr(industriesget,industries)
{
var flag=false;
for(var i=0;i<industriesget.length;i++)
{
if(industries.includes(industriesget[i])) {
flag = true;
}
}
return flag;
}

Fill tree json data to dropdown box

I have json data in tree format:
[
{
"beer_names": [
"Apple Ale",
"Bad Seed Pumpkin Ale"
],
"brewery": "Basil T's Brew Pub and Italian Grill"
},
{
"beer_names": [
"5 C's IPA",
"Bottle Rocket IPA",
"Kate The Great Russian Imperial Stout",
"Wheat Wine"
],
"brewery": "Portsmouth Brewery"
},
{
"beer_names": [
"Black Forest Dunkelweizen",
"Equinox E.S.B.",
"Evolutionary IPA",
"G.E. Lite",
"Nut Brown",
"Red",
"Smoked Porter"
],
"brewery": "Glen Ellyn Sports Brew"
}
]
So I want to fill this data to Dropdown box like this:
--Basil T's Brew Pub and Italian Grill
--------Apple Ale
--------Bad Seed Pumpkin Ale
--Portsmouth Brewery
--------5 C's IPA
--------Bottle Rocket IPA
--------Wheat Wine
--------Kate The Great Russian Imperial Stout
--Glen Ellyn Sports Brew
--------Black Forest Dunkelweizen
--------Equinox E.S.B.
--------Evolutionary IPA
--------G.E. Lite
--------Nut Brown
--------Red
--------Smoked Porter
Or a tree view allow for select value name of child equipment?
Here you are:
var data = [{
"beer_names": [
"Apple Ale",
"Bad Seed Pumpkin Ale"
],
"brewery": "Basil T's Brew Pub and Italian Grill"
}, {
"beer_names": [
"5 C's IPA",
"Bottle Rocket IPA",
"Kate The Great Russian Imperial Stout",
"Wheat Wine"
],
"brewery": "Portsmouth Brewery"
}, {
"beer_names": [
"Black Forest Dunkelweizen",
"Equinox E.S.B.",
"Evolutionary IPA",
"G.E. Lite",
"Nut Brown",
"Red",
"Smoked Porter"
],
"brewery": "Glen Ellyn Sports Brew"
}];
$.each(data, function(index, value) {
var str = '<optgroup label="' + value["brewery"] + '">';
$.each(value['beer_names'], function(index, value) {
str += '<option value="' + value + '">' + value + '</option>';
});
str += '</select>';
$('select').append(str);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select></select>
Hope this helps.
You can see this link :
http://www.jeasyui.com/demo/main/index.php?plugin=ComboBox
then you select Group ComboBox from left panel.
Maybe help you

Accessing Nested arrays in Json using .$each

So I'm having a problem accessing my json when its in a nested array. I previously had json set up like this with just one array and my .$each function worked perfectly. However I'm having trouble modifying it for this.
Json:
{
"tcontent": [{
"Name": "Septicaemia",
"url":"<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/septicaemia.jpg);'>",
"Variations": [{
"condition":"Community-acquired",
"organisms":"Staph. aureus",
"antimicrobial":"Flucloxacillin ",
"alternative":"(non anaphylaxis): ",
"comments": "Perform full septic screen."
}, {
"Condition":"Community-acquired if intra- abdominal source suspected",
"Organisms":"Predominantly Gram negatives and anaerobes Enterococci may also feature",
"Antimicrobial":"Co-amoxiclav 1.2g iv tds",
"Comments":"Perform full septic screen"
}, {
"Condition":"Healthcare-associated",
"Organisms":"Varies",
"Antimicrobial":"Piperacillin",
"Alternative":"Seek advice from Consultant Microbiologist",
"Comments":"Always"
}]
}, {
"Name": "Infective Endocarditis (IE) (pending blood culture results)",
"url":"<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/endocarditis.jpg);'>"
}, {
"Name": "Central Nervous System Infections",
"url":"<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/cns.jpg);'>"
}, {
"Name": "Skin and Soft Tissue Infections",
"url": "<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/skin.jpg);'>"
}, {
"Name": "Diabetic patients with foot infections",
"url": "<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/foot.jpg);'>"
}, {
"Name": "Bone and Joint Infections",
"url": "<a>",
"image":"<<div class='grid' style='background-image:url(img/anatomy/bone.jpg);'>"
}, {
"Name": "Intravascular Line Infections",
"url": "<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/intravascular.jpg);'>"
}, {
"Name": "Urinary Tract Infections",
"url": "<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/urinary.jpg);'>"
}, {
"Name": "Respiratory Tract Infections",
"url": "<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/respiratory.jpg);'>"
}, {
"Name": "Gastrointestinal Infections",
"url": "<a>",
"image":"<div class='grid' style='backgroundimage:url(img/anatomy/gastrointestinal.jpg);'>"
}]
}
Here's my javascript to access it.
$(function (){
var imp = "Json/therapy.json"
$.getJSON(imp, function(data) {
var info = "<br>";
$.each(data.tcontent, function(i, item) {
if(item.Name=='Septicaemia'){
var search = item.Variations;
$.each(item.Variations, function(j, subitem) {
info += subitem.condition + subitem.organisms + subitem.antimicrobial + subitem.alternative + subitem.comments
});
$(info).appendTo(".menu");
//alert(item)
};
});
});
});
I've tried a many variations on the var search but nothing seems to be working. I researched a lot of similar problems to this and I've been stuck on this for too long. Any light that can be shed on the situation would be much appreciated!
2 reasons why it doesn't work.
First of all javascript is case sensitive, Your variations differ.
subitem.condition fails on :
"Condition":"Community-acquired if intra- abdominal source suspected",
"Organisms":"Predominantly Gram negatives and anaerobes Enterococci may also feature",
"Antimicrobial":"Co-amoxiclav 1.2g iv tds",
"Comments":"Perform full septic screen"
So change "Condition" to "condition", etc.etc.
second reason is the
Change $(info).appendTo(".menu"); to $(".menu").append(info);
Why?
$(".menu").append(info) Will just paste the string in the selected DOM element.
But you use
$(info)... and jquery does all kinds of fancy stuff now.
It tries to either use it as DOM selector, or create a new element.
Because your info starts with <br> $(info) tries to create a DOM element and it removes all text. Leaving just <br> because br cannot contain content.
Try to remove the initial <br> then you will see following error:
Uncaught Error: Syntax error, unrecognized expression:Community-acquiredStaph. aureusFlucloxacillin...
For example if you would type $("hahaha") , Jquery will try to find the tag <hahaha>, So when you remove the <br> your $(info) is looking for the tag <Community-acquiredStaph. aureusFlucloxacillin...>.
But because your string would then contain weird characters like "-()." It will fail. Hence the above error.
So you can only add html like this:
$("<span>hahah</span>").appendTo($(".menu"));
Or use selector
$("#myDiv").appendTo($(".menu"));
An example when $(info).appendTo(".menu"); working is:
$.each(data.tcontent, function(i, item) {
if(item.Name=='Septicaemia'){
var search = item.Variations;
$.each(item.Variations, function(j, subitem) {
var info = "<p>" + subitem.condition + subitem.organisms + subitem.antimicrobial + subitem.alternative + subitem.comments + "</p>";
$(info).appendTo(".menu");
});
}
});
Using the following json:
http://pastebin.com/Bzpix1ai

Categories

Resources