简体   繁体   中英

Javascript sort array of objects according to string and outputing statements

I am trying iterate over this array and I'm trying to output the following sentences and Im not sure where to go from here

 const coffees = [ 
    "light colombian roast", "hawaiian dark roast", "guatemalan blend medium roast",
    "madagascar espresso roast", "jamaican dark blue", "jamaican medium roast",
    "salvador robusto light", "bali espresso roast"

For light roast, output "I'll have the xxx and drink it black" For medium roast, output "I'll have the xxx and add cream only" For dark OR espresso roast, output "I'll have the xxx and add cream and sugar"

I cant figure out how to output each coffee blend into its own statement after sorting them this was my last attempt but I'm puzzled

let lightCoffee = 0
 let mediumCoffee = 0
 let darkCoffee = 0


 for(const prefered of coffees){

  if (prefered.includes("light"){
    lightRoast = `I'll have the ${prefered} and drink it black`
    lightCoffee.push(lightRoast)
  }
  console.log(lightCoffee)

As your coffee variants don't have a uniform scheme where the keyword is, all you can do is either go through all possible keywords one after the other or filter the strings for anything but the keywords.

For example you could do this filtering trick:

 const coffees = [ "light colombian roast", "hawaiian dark roast", "guatemalan blend medium roast", "madagascar espresso roast", "jamaican dark blue", "jamaican medium roast", "salvador robusto light", "bali espresso roast" ]; const mappings = { light: full => `I'll have the ${full} and drink it black`, medium: full => '', dark: full => '', espresso: full => '', }; const mapped = coffees.map(coffee => { const [full, match] = coffee.match(/.*(light|medium|dark|espresso).*/); return mappings[match](full); }); console.log(mapped);

So what I'm doing here is map all the array elements from the coffees array using a function. In that function I used a regex pattern matching to get both the full coffee variant string and just the keyword at once. I then prepared an object with mappings from keyword to a function that given a full variant string as input will return a template string with the coffee variant replaced into it.

This is using Arrow functions and Array destructuring here, all of which is part of ES2015 and has landed in Browsers newer than 2017 I guess. (Ie it's not available in IE11)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM