-1

I would like to know how to filter data from the following array

0: {Id: 30008, Item: " Rice"}
1: {Id: 30009, Item: " Beans"}
2: {Id: 30011, Item: " Beans"}
3: {Id: 30016, Item: " Rice"}"

I would like to get the count of all items that are repeating in the above. My idea is get the count and append this number in some div in the page. The page contains the following div

<div className="quantity">
    <input type="number" defaultValue="{1}" min="{1}" className="quantity-field" id="default-quantity" />
</div>
Robert
  • 29
  • 6

1 Answers1

0

Use reduce for collect and count your items, like this:

const data = [{Id: 30008, Item: " Rice"},
{Id: 30009, Item: " Beans"},
{Id: 30011, Item: " Beans"},
{Id: 30016, Item: " Rice"}]

const groupedDataObj = data.reduce((acc,rec)=>{
    acc[rec.Item] = typeof acc[rec.Item] === 'undefined'? 1: acc[rec.Item]+1
    return {...acc}
},{})

const groupedDataArray = Object.keys(groupedDataObj).map((key)=>({[key]: groupedDataObj[key]}))

See full example in the playground: https://jscomplete.com/playground/s545971

Denis Stukalov
  • 1,236
  • 1
  • 6
  • 11