Search code examples
javascriptarraysstringword-frequency

Create List of Words that Appear In String Without Spaces - Account For When Word Appears More Than Once


As per this Codewars challenge, I need to create some simple logic for keeping track of all of the words that appear in a string.


INSTRUCTIONS

Some new cashiers started to work at your restaurant.

They are good at taking orders, but they don't know how to capitalize words, or use a space bar!

All the orders they create look something like this:

"milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza"

The kitchen staff are threatening to quit, because of how difficult it is to read the orders.

Their preference is to get the orders as a nice clean string with spaces and capitals like so:

"Burger Fries Chicken Pizza Pizza Pizza Sandwich Milkshake Milkshake Coke"

The kitchen staff expect the items to be in the same order as they appear in the menu.

The menu items are fairly simple, there is no overlap in the names of the items:

  1. Burger
  2. Fries
  3. Chicken
  4. Pizza
  5. Sandwich
  6. Onionrings
  7. Milkshake
  8. Coke

EDIT Following the .match() logic, I've created an array of all items that appear in the input. But I don't know the quickest way to sort them according to their order of appearance in the original string:

function getOrder(order) {
  
  let menu = ['Burger', 'Fries', 'Chicken', 'Pizza', 'Sandwich', 'Onionrings', 'Milkshake', 'Coke'];
  
  let finalOrder = order.split(/(burger|fries|chicken|pizza|sandwich|onionrings|milkshake|coke)/i);
  finalOrder = finalOrder.filter((element) => element !== null || element !== "");
  finalOrder = finalOrder.map((element) => element.charAt(0).toUpperCase() + element.slice(1));
  finalOrder = finalOrder.sort((a, b) => {
    if (menu.indexOf(a) > menu.indexOf(b)) {
      return 1;
    }
    else {
      return -1;
    }
  });
  return finalOrder.join(" ").trim(/\s/);
}

console.log(getOrder("milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza"));


Solution

    1. Create an array of all matching items that exist within the input string
    2. Turn the first letter of all items in the array to Uppercase, so that they match the items in the menu array exactly.
    3. Sort the items according to their order in the menu array.
    4. Return the array joined into a string.

    function getOrder(input) {
        
      let menu = ['Burger','Fries','Chicken','Pizza','Sandwich','Onionrings','Milkshake','Coke'];
      let items = input.match(/(burger|fries|chicken|pizza|sandwich|onionrings|milkshake|coke)/gi);
      items = items.map((element) => element.charAt(0).toUpperCase() + element.slice(1));
      items = items.sort((a, b) => {
        if (menu.indexOf(a) > menu.indexOf(b)) {
          return 1;
        }
        else {
          return -1;
        }
      });
      return items.join(" ");
    }
    
    console.log(getOrder("milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza"));