Skip to content

Instantly share code, notes, and snippets.

@timbuckley
Last active January 28, 2016 23:42
Show Gist options
  • Save timbuckley/ebc6bbe42ac89c0a730b to your computer and use it in GitHub Desktop.
Save timbuckley/ebc6bbe42ac89c0a730b to your computer and use it in GitHub Desktop.
var menuInput = "Lunch Box,Roast Beef\nTotto Ramen,Miso Noodles\nLunch Box,Turkey\nTotto Ramen,Kimchee\nEl Centro,Enchiladas\nBengal Tiger,Garlic Naan\nLunch Box,Tomato Avocado\nTotto Ramen,Spicy Noodles\nLunch Box,Soup of the Day\nBengal Tiger,Saag Paneer\nTotto Ramen,Pork Bun\nIsland Burgers and Shakes,Fries\nBengal Tiger,Chicken Tikka Masala\nEl Centro,Chips and Guacamole\nIsland Burgers and Shakes,Chocolate Milkshake\nTotto Ramen,Hot Tea\nIsland Burgers and Shakes,Cheddar Burger\nBengal Tiger,Chicken Vindaloo\nIsland Burgers and Shakes,Garden Burger\nEl Centro,Fajitas";
// Nested list of restaurant-item pairs.
var menuObj = {},
pairs = menuInput
.split("\n")
.map(function(pair) {return pair.split(',')}); //in ES6: pair => pair.split(',')
// Build into menuObj.
pairs.forEach(function(pair) {
var key = pair[0]
var val = pair[1] // in ES6: let [key, val] = pair
if (menuObj[key] === undefined) {
menuObj[key] = [val]
} else {
menuObj[key].push(val)
}
})
// Print out results by key.
Object.keys(menuObj) // Trick to get keys array of menuObj
.sort() // Alphabetical restaurant names
.forEach(function(restaurant) {
console.log(restaurant) // Print restaurant name
menuObj[restaurant]
.sort() // Alphabetical menu items
.forEach(function(item, idx) {
console.log((idx + 1) + ") " + item) // Print menu item, plus an index num e.g.: 1) Tapioca
})
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment