0

I am trying to show a order list in html when I load the order list from the backend. In a for loop the jquery should look if a ordered food exist multiple times.

Currently the list looks like this:

  • Pizza
  • Soup
  • Pizza
  • Pasta

I want it to show this way:

  • 2x Pizza
  • Soup
  • Pasta

I already tried something like this

const allEqual = arr => arr.every(v => v === arr[0]);
allEqual([1,1,1,1]);
Cedzy
  • 46
  • 5

1 Answers1

1

Here's one approach:

  • Create an object named itemCount
  • Loop over the original list of items
  • For every item in the list, add a property to the itemCount object named after the item and set its value to 1. Check if the property already exists and if it exists, add 1 to the value.
  • After you finish iterating over the list, start iterating over the itemCount object, using a method like Object.keys or Object.entries.
  • For every property in the object, concatenate the property name along with the property value and append the "x" character at the end of the value:

{ Pizza: 3, Soup: 1, ... } => "3x Pizza", etc.

There are many ways to approach this, but I'm just sharing a simple one to try starting with.

Kostas Minaidis
  • 4,681
  • 3
  • 17
  • 25