Search code examples
reactjsfilterreducearray.prototype.mapsubtotal

React - How to get subtotal of mapped items after filtering them?


I am trying to get subtotal of items after filtering them:

const total = (allItems.reduce((total, item) => total + item.price, 0)).toFixed(2);

This is the filter:

{allItems
  .filter((items) => {
    if(items.name.toLowerCase().includes(query)){
      return items
      } 
   })
   .map((item, i) => {
        return(
        <div className='item' key={Math.random()} id={Math.random()}> 
          <div className='text'>{i+1}. {item.name} </div>
          <div className='number'> {(Math.round(item.price * 100) / 100).toFixed(2)} </div>
        </div>
      )})}

Solution

  • You could isolate your filter function in a const and then do the operation on it:

    const filteredItems = allItems
      .filter((items) => {
        if(items.name.toLowerCase().includes(query)){
          return items
          } 
       })
    
    const filteredTotal = filteredItems.reduce((total, item) => total + item.price, 0)).toFixed(2)
    

    and then in your render:

    {filteredItems.
       .map((item, i) => {
            return(
            <div className='item' key={Math.random()} id={Math.random()}> 
              <div className='text'>{i+1}. {item.name} </div>
              <div className='number'> {(Math.round(item.price * 100) / 100).toFixed(2)} </div>
            </div>
          )})}