Compare two string objects for matched string - javascript

I was just wondering how I could search and compare two string object and check if either contains a matching string.
I have an associative array containing terms and explanations.
I also have this array broken into two objects "keys"(keys showing the key of the associative array) and "values"(values showing the value of each key in array).
I have another associative array containing a dish and its explanation.
I have split the dish's description into separate words put them into an object.
What I would like to do now is check for every word in descsplit search the TermList and return explanation of term found if found.
eg. free-range is contained in dish explanation, check if there is a match for free-range in TermList and return the value(explanation) of free-range.
Any help would be greatly appreciated, Thanks.
var TermList= {
'Al dente' : 'Al dente : Pasta cooked until just firm. From the Italian "to the tooth." ',
'Bake' : 'Bake: To cook food in an oven, surrounded with dry heat; called roasting when applied to meat or poultry.',
'Barbecue' : 'Barbecue: To cook foods on a rack or a spit over coals.',
'Baste' : 'Baste: To moisten food for added flavor and to prevent drying out while cooking.',
'Batter' : 'Batter: An uncooked pourable mixture usually made up of flour, a liquid, and other ingredients.',
'Beat' : 'Beat: To stir rapidly to make a mixture smooth, using a whisk, spoon, or mixer.',
'Blanch' : 'Blanch: To cook briefly in boiling water to seal in flavor and color; usually used for vegetables or fruit, to prepare for freezing, and to ease skin removal.',
'Blend' : 'Blend: To thoroughly combine 2 or more ingredients, either by hand with a whisk or spoon, or with a mixer.',
'Boil': 'Boil: To cook in bubbling water that has reached 100 degrees Celcius.',
'Bone' : 'Bone: To remove bones from poultry, meat, or fish.',
'Bouquet garni' : 'Bouquet garni: A tied bundle of herbs, usually parsley, thyme, and bay leaves, that is added to flavor soups, stews, and sauces but removed before serving.',
'Braise' : 'Braise: To cook first by browning, then gently simmering in a small amount of liquid over low heat in a covered pan until tender.',
'Bread': 'Bread: To coat with crumbs or cornmeal before cooking.',
'Free-range': 'Free-range: (Of livestock, especially poultry) kept in natural conditions, with freedom of movement/ (Of eggs) produced by free-range poultry.'
};
var values = []; // Creating an object for the values of the terms in TermList
var keys = []; // Creating an object for the keys of the terms in TermList
//function to assign the keys of terms to object keys.
function showkey() {
for (var key in TermList) {
if (TermList.hasOwnProperty(key)) {
keys.push(key);
}
}
//function that shows the value of each key in TermList.
function showValue(){
for( var value in TermList){
values.push(TermList[value]);
}
showkey();
showValue();
var DishList={
"Chicken and Stuffing Sandwich": "Chicken and Stuffing Sandwich: Succulent Sandwich made from free-range chicken and fresh breadcrumbs mixed with mayonnaise",
"Eggs Benedict": "Poached eggs served with spinach and hollandaise sauce"
};
var descsplit = [];
function SplitDesc() {
for (var value in DishList) {
descsplit.push(DishList[value].split(/[\s.,?!:]+/)); // Splits the values of the key up in Dishlist, and puts them into array.Also makes them avoid punctuations while splitting.
}
}
SplitDesc();
//For every word in descsplit search the TermList and return explanation of term found if found

Not tested fully, but this may work
var TermList= {
'Al dente' : 'Al dente : Pasta cooked until just firm. From the Italian "to the tooth." ',
'Bake' : 'Bake: To cook food in an oven, surrounded with dry heat; called roasting when applied to meat or poultry.',
'Barbecue' : 'Barbecue: To cook foods on a rack or a spit over coals.',
'Baste' : 'Baste: To moisten food for added flavor and to prevent drying out while cooking.',
'Batter' : 'Batter: An uncooked pourable mixture usually made up of flour, a liquid, and other ingredients.',
'Beat' : 'Beat: To stir rapidly to make a mixture smooth, using a whisk, spoon, or mixer.',
'Blanch' : 'Blanch: To cook briefly in boiling water to seal in flavor and color; usually used for vegetables or fruit, to prepare for freezing, and to ease skin removal.',
'Blend' : 'Blend: To thoroughly combine 2 or more ingredients, either by hand with a whisk or spoon, or with a mixer.',
'Boil': 'Boil: To cook in bubbling water that has reached 100 degrees Celcius.',
'Bone' : 'Bone: To remove bones from poultry, meat, or fish.',
'Bouquet garni' : 'Bouquet garni: A tied bundle of herbs, usually parsley, thyme, and bay leaves, that is added to flavor soups, stews, and sauces but removed before serving.',
'Braise' : 'Braise: To cook first by browning, then gently simmering in a small amount of liquid over low heat in a covered pan until tender.',
'Bread': 'Bread: To coat with crumbs or cornmeal before cooking.',
'Free-range': 'Free-range: (Of livestock, especially poultry) kept in natural conditions, with freedom of movement/ (Of eggs) produced by free-range poultry.'
};
var DishList={
"Chicken and Stuffing Sandwich": "Chicken and Stuffing Sandwich: Succulent Sandwich made from free-range chicken and fresh breadcrumbs mixed with mayonnaise",
"Eggs Benedict": "Poached eggs served with spinach and hollandaise sauce"
};
var keys = Object.keys(TermList);
for(var key in DishList){
var val = DishList[key];
for(var iIndex=0;iIndex<keys.length ;iIndex++){
var term = keys[iIndex];
var regx = new RegExp('\\b'+term+'\\b',"gi");
var found = null;
while((found = regx.exec(val))!=null){
console.log('Found term "'+ term+ '" at index '+found.index);
}
}
}

Related

Understand the following exercise of js loops and strings in array

I'm trying to make sense of the following javascript exercise but can't seem to make sense of it, all I know for now is that I can access each string with "acrostic[i]" where the i would be the number in the array but don't know where to go from there.
const acrostic = [
"Give me your patience, sister, while I frame",
"Exact in capitals your golden name;",,
"Or sue the fair Apollo and he will",
"Rouse from his heavy slumber and instill",
"Great love in me for thee and Poesy.",
"Imagine not that greatest mastery",
"And kingdom over all the Realms of verse,",
"Nears more to heaven in aught, than when we nurse",
"And surety give to love and Brotherhood.",
" ",
"Anthropophagi in Othello's mood;",
"Ulysses storm'd and his enchanted belt",
"Glow with the Muse, but they are never felt",
"Unbosom'd so and so eternal made,",
"Such tender incense in their laurel shade",
"To all the regent sisters of the Nine",
"As this poor offering to you, sister mine.",
" ",
"Kind sister! aye, this third name says you are;",
"Enchanted has it been the Lord knows where;",
"And may it taste to you like good old wine,",
"Take you to real happiness and give",
"Sons, daughters and a home like honied hive."
];
/* Declare a variable that will return the final string */
let georgianaAugustaKeats = "acrostic[i][0]";
for (let i = 0; i < acrostic.length; i += 1) {
/* add each first character of each string to the array
to the georgianaAugustaKeats variable*/
}
console.log(georgianaAugustaKeats);
While the other answers are correct, I think they're not beginner-friendly.
If all you need to do for the exercise is to replace the part commented in the for loop, then it's simply:
let georgianaAugustaKeats = "";
for (let i = 0; i < acrostic.length; i += 1) {
georgianaAugustaKeats += acrostic[i][0];
}
console.log(georgianaAugustaKeats);
NOTE: The third string ends with an empty ,,, I'm not sure that's intentional. That will cause this code to generate an error (because the string is empty, there's no first element). You can easily account for that, but I think it's another question.
You can use map() with some destructuring to generate an array containing the first letter of every line, and then join() that array into a string:
const acrostic = [
"Give me your patience, sister, while I frame",
"Exact in capitals your golden name;",
"Or sue the fair Apollo and he will",
"Rouse from his heavy slumber and instill",
"Great love in me for thee and Poesy.",
"Imagine not that greatest mastery",
"And kingdom over all the Realms of verse,",
"Nears more to heaven in aught, than when we nurse",
"And surety give to love and Brotherhood.",
" ",
"Anthropophagi in Othello's mood;",
"Ulysses storm'd and his enchanted belt",
"Glow with the Muse, but they are never felt",
"Unbosom'd so and so eternal made,",
"Such tender incense in their laurel shade",
"To all the regent sisters of the Nine",
"As this poor offering to you, sister mine.",
" ",
"Kind sister! aye, this third name says you are;",
"Enchanted has it been the Lord knows where;",
"And may it taste to you like good old wine,",
"Take you to real happiness and give",
"Sons, daughters and a home like honied hive."
];
const result = acrostic.map(([first]) => first).join('');
console.log(result);
You can use Array.prototype.reduce() combined with Destructuring assignment
Code:
const acrostic = [
'Give me your patience, sister, while I frame',
'Exact in capitals your golden name;',
,
'Or sue the fair Apollo and he will',
'Rouse from his heavy slumber and instill',
'Great love in me for thee and Poesy.',
'Imagine not that greatest mastery',
'And kingdom over all the Realms of verse,',
'Nears more to heaven in aught, than when we nurse',
'And surety give to love and Brotherhood.',
' ',
"Anthropophagi in Othello's mood;",
"Ulysses storm'd and his enchanted belt",
'Glow with the Muse, but they are never felt',
"Unbosom'd so and so eternal made,",
'Such tender incense in their laurel shade',
'To all the regent sisters of the Nine',
'As this poor offering to you, sister mine.',
' ',
'Kind sister! aye, this third name says you are;',
'Enchanted has it been the Lord knows where;',
'And may it taste to you like good old wine,',
'Take you to real happiness and give',
'Sons, daughters and a home like honied hive.',
]
/* Declare a variable that will return the final string */
const result = acrostic.reduce((a, [f]) => a + f, '')
console.log(result)

removeStr.indexOf not removing all requested elements

I am still very much learning Javascript/Google Apps Script, but have created a javascript which takes certain google sheets relating to orders for a business, removes certain data not needed and then creates a list of the remaining ordered items by each item. This has all worked well for the first two of these google sheets, but when I come to the the third, I have an issue in that the removeStr.indexOf is not removing all the data I would expect it too and was therefore hoping someone could tell me where I am going wrong please?
Here is an image of the raw data reduced to fit
From the above the function firstly creates an array which produces the following
Status,NaN,Date Submitted,NaN,Name,NaN,Phone,NaN,Delivery Required?,NaN,Address ,NaN,GLATT SUMMARY,NaN,MH SUMMARY,NaN,GILBERTS SUMMARY,NaN,SMOKED SALMON SUMMARY,NaN,DOVIDS SUMMARY,NaN,Roaster,3,Wrapped Cut Up,1,Wrapped Cut Up Skinned,0,Carcus
,0,Half Hen,0,Mince,0,Lean Mince,2,Chicken Mince,0,Chicken Wings (8),0,Drumsticks (4),1,Thighs (4),0,Breasts (2),4,Pargiot (6),0,Hinds (2),0,Cumberland,2,Burger (4),0,Diced Steak,2,Fairy Steaks (Pack),1,Ribeye Steak,0,Bola,0,Lamb Chops (4),3,Shoulder Chops (2),0,Lamb Shanks (2),0,Shoulder Lamb (off bone),0,Shoulder Lamb (bone in),0,Turkey Thigh,0,Turkey Leg,0,Roaster Crown,0,Roaster in Tin,0,Meatballs 12,0,Meatballs Family,0,Lamb Shwarma,0,Thick Chops (4),0,Salmon 200g,1,Salmon 100g,2,Gefilte,0,Fishball (L),0,Fishball (S),0,ADDITIONAL ITEMS? (subject to availability),NaN
From the above array, the next stage is the to remove the unnecessary elements in two or so stages by firstly removing the not required strings via a removeStr.indexOf and then secondly by removing the NaN's linked to those remove strings. This is done as followed:-
// This array contains strings that needs to be removed from main array for Meat_Fish Order
var removeStr = ['Status' ,'Date Submitted' ,'Name' , 'Phone' , 'Delivery Required?' , 'Address ', 'GLATT SUMMARY' , 'MH SUMMARY' ,'GILBERTS SUMMARY' , 'SMOKED SALMON SUMMARY' , 'DOVIDS SUMMARY' , 'ADDITIONAL ITEMS? (subject to availability)'];
ordered = ordered.filter(function(val){
return (removeStr.indexOf(val) == -1 ? true : false)
});
var ordered = ordered.filter(function(value) {
return !Number.isNaN(value);
});
The above removeStr.indexOf is semi successfully, but for some reason is not removing Address, SMOKED SALMON SUMMARY and DOVIDS SUMMARY, as you can see below.
Address ,SMOKED SALMON SUMMARY,DOVIDS SUMMARY,Roaster,3,Wrapped Cut Up,1,Wrapped Cut Up Skinned,0,Carcus
,0,Half Hen,0,Mince,0,Lean Mince,2,Chicken Mince,0,Chicken Wings (8),0,Drumsticks (4),1,Thighs (4),0,Breasts (2),4,Pargiot (6),0,Hinds (2),0,Cumberland,2,Burger (4),0,Diced Steak,2,Fairy Steaks (Pack),1,Ribeye Steak,0,Bola,0,Lamb Chops (4),3,Shoulder Chops (2),0,Lamb Shanks (2),0,Shoulder Lamb (off bone),0,Shoulder Lamb (bone in),0,Turkey Thigh,0,Turkey Leg,0,Roaster Crown,0,Roaster in Tin,0,Meatballs 12,0,Meatballs Family,0,Lamb Shwarma,0,Thick Chops (4),0,Salmon 200g,1,Salmon 100g,2,Gefilte,0,Fishball (L),0,Fishball (S),0
I thought the issue was down possible to case, additional spacing, or something like that, but have matched exactly and still no joy.
As well as sorting this would be good to know if there is anything within Javascript which is of use to take away an potential issues with case sensitivity and additional spacing. Is there anything?
Big thanks in advance
to correct errors of whitespace and capital letters let's standardize all texts before:
const standardize = val => {
if (typeof val === 'string') return val.replace(/\s/g, '').toLowerCase()
return val
}
const standardizedRemoveStr = removeStr.map(standardize)
const res = ordered.filter(val => {
return !standardizedRemoveStr.includes(standardize(val)) && !Number.isNaN(val)
})

Using Arithmetic operators in parameters of a Function

I tried to do it but didn't work
I want to achieve something like this:
function clubMember(clubName, women + men, women, men) {
const club = `${clubName} club has ${women + men} members including ${women} Women and ${men} Men`
return club
}
The answer is: no, you can't put arithmetic operators as a parameter.
As far as I know, there are no languages that gives you ability to calculate as a parameter.
However, you could do something like this if you wish:
function clubMember(clubName, total, women, men) {
const club = `${clubName} club has ${total} members including ${women} Women and ${men} Men`;
return club;
}
clubMember(club, women+men, women, men);

I am trying to scrape amazon, and stop at a specific number

So this is my code
if (body.included != null && body.included.length > 0) {
let genres = '';
for(let i = 0; i < body.included.length; i++) {
genres += body.included[i].attributes.title;
if(i != body.included.length - 1) {genres += ', ';}
}
embed.addField('GENRES', [`${genres}`,], true);
}
this is the results whenever i search anything with this it gives me this:
Comedy, Kids, Fantasy, Fantasy World, Erotic Torture, Loli, Nudity, Bdsm, Bondage, Sex, Past, Plot Continuity, Violence, Military, Mecha, Historical, Action, Romance, Science Fiction, World War II, Japan, Asia, Piloted Robot, Alternative Past, Steampunk, Gunfights, Alien, War, Robot, Adventure, Space Travel, Cyborg, Crime, Other Planet, Humanoid Alien, Future, Space, Contemporary Fantasy, Vampire, Slice of Life, Detective, Bounty Hunter, Magic, Present, Demon, Super Power, Drama, Anime Influenced, Earth, Love Polygon, Angst, High School, School Life
Has this a example because other types searches comes with 1 or 2 or decent amount of genres where it doesn't have like 40 of them
like this one
Ninja, Fantasy World, Adventure, Action, Comedy, Martial Arts, Super Power, Romance, Disaster, Shounen, Love Polygon, Angst, Plot Continuity, Parallel Universe, Fantasy
So what i need help is how do i make it stop in a certain number where it wont give me 40 of them instead 10 or less
You could change the loop condition but still need to watch out for the length of the body.included array for cases where it has fewer than 10 elements. Try the following:
const MAX_GENRES = 10;
if (body.included && body.included.length) {
const max = Math.min(MAX_GENRES, body.included.length);
const genres = [];
let i = 0;
while (i < max) {
genres.push(body.included[i].attributes.title);
i += 1;
}
embed.addField('GENRES', [genres.join(',')], true);
}
This should achieve what you're after. I don't know the signature for embed.addField() but are you certain that the second argument should be a single-element array containing a string? Could be but seems weird. If the function calls for an array of strings use:
embed.addField('GENRES', genres, true);

Is creating instance of object same as creating object of same type?

I have to create an object, three instances of objects and arrays.
Create a cruise object that has the following properties:
Cruise Date,
Cruise Destination,
Cruise Description,
Cruise URL,
Ship Name,
Ship Description,
Ship URL,
Price
Make three instances of the cruise object.
Create an array of the three instances.
According to my understanding I created one cruise object with all properties mentioned and I have to create three more instances of object.
I did the following. Does creating instances means creating object of same type?
function Cruise(cruise_Date, cruise_Destination, cruise_URL, ship_Name, ship_Description, ship_url, price ) {
this.cruise_Date = cruise_Date;
this.cruise_Destination = cruise_Destination;
this.cruise_URL = cruise_URL;
this.ship_Name = ship_Name;
this.ship_Description = ship_Description;
this.ship_url = ship_url;
this.price = price
}
var myCruise = new cruise("16 March 2018",
'4 Night Bahmas cruise ',
"You know the name, the laid-back attitude and where to find them, but you’ll just have to visit The Bahamas to truly appreciate this classic cruise destination. On this 700-strong string of sun-splashed islands dotting the blue Atlantic, the living’s easy. (And it’s not bad on a Bahamas cruise either!) The central port of Nassau is the bustling capital of the country — bustling is a relative term, of course — while Freeport is all chill, all the time. And nothing is as delightfully desolate as Half Moon Cay and Princess Cays: pure private-destination paradise",
"https://www.ncl.com/cruise-destinations/bahamas-florida-cruises?cid=PS_TSI_CAL_DST_GOO-g_LEN_SRH_DESTBAF_3%20night%20bahamas%20cruise_NA_189086496943&kshid=998d4956-0345-4c42-88fb-0f1ce25bfbf9&kwid=659072&anchor=NA&gclid=Cj0KEQjw3rfOBRDJruDR8Ljm7e0BEiQAam-GsPAAXfpiBInuQfwSq6ZOe4U2KBmlRbc08kFl-gFJIBQaAtvn8P8HAQ",
'Majesty of the sea ', "MS Majesty of the Seas is a Sovereign-class cruise ship owned by Royal Caribbean Cruises Ltd and operated by Royal Caribbean International. ", "https://www.royalcaribbean.com/cruise-ships/majesty-of-the-seas",
'$' + 169);
var myCruise2 = new cruise("Cruise_Date", "Cruise_Destination", "Cruise_Description", "Cruise_URL", "Ship_Name", "Ship_Description", "Ship_URL", "Price");
var myCruise3 = new cruise("Cruise_Date", "Cruise_Destination", "Cruise_Description", "Cruise_URL", "Ship_Name", "Ship_Description", "Ship_URL", "Price");
list = new Array("Departs", "Destination", "Ship", "Price from");
instances = new Array(myCruise, myCruise2, myCruise3);
function displayList(the_date, ) {
// body...
}
expected output:
Your code in creating objects has a few problems. You would need to have an object constructor function named cruise() for that to work. Usually you capitalize object constructor functions. Also, I doubt they intended for you to give values of each property that are the same as the names of the properties. If you are giving an instance of an object of a cruise, you would give it an actual destination like "The Bahamas", etc. An object constructor function would look something like this:
function Cruise(date,destination,descr,url,name,price){
this.cruiseDate = date;
this.cruiseDestination = destination;
this.cruiseDescription = descr;
this.cruiseUrl = url;
this.cruiseName = name;
this.cruisePrice = price;
}
As for creating an array of objects, after you make the instances of the objects with actual values in them similar to how you did them, you could just put them in an array literal, unless you were supposed to do it another way.
var instances = [myCruise,myCruise2,myCruise3];

Categories