Home > Software design >  How to display duplicate array values only once in React.js
How to display duplicate array values only once in React.js

Time:08-11

I have a Bill To Print but in Bill I have 'Products' array object in which I want, I have 3 products array then product name, price, discount, etc. are same then it should show only one array (line) but in 'Products' array I have a 'SrNo.' column which means each product has unique serial number so it should product name, price, discount, etc. show in one line and 'SrNo.' column shows 3 rows. Currently I'm using map() to display array values but it showing like this

Products arrays

My Bill_Preview.js (Frontend)

      <tr>
        <td style={{width:"1%"}}>Sr<br></br>No.</td>
        <td >Description Of Goods</td>
        <td >Qty</td>
        <td >Rate</td>
        <td >Disc %</td>
        <td >Amount</td>
        </tr>
        
        {/* Data row */}
  {DataForPreview &&
  DataForPreview.map((data, Id) => (

     // This Row all data i want only once if its same product except 'Prod_SrNo'

        <tr>
        <td >{Id   1}.</td>
        <td >
          {data.Product_Comp} {data.Product}
          <br></br>
          {data.Prod_SrNo}
          <br></br>
        </td>
        <td >1</td>
        <td >{data.Price}</td>
        <td >{data.Discount}</td>
        <td >{(data.Price - (data.Price * data.Discount) / 100).toFixed(2) }</td>
        
       
        </tr>
    ))}

CodePudding user response:

you can filter the duplicate values from the array before mapping:

function filterDuplicates(arr){
return arr.filter((item, index) => arr.findIndex(data=> data.Product === item.Product &&  data.Product_Comp === item.Product_Comp) === index);
}

function findDuplicatesRows(data){
return DataForPreview.filter(item => (data.Product === item.Product &&  data.Product_Comp === item.Product_Comp))
}


filterDuplicates(DataForPreview).map((data, Id) => (
   <tr>
         <td >{Id   1}.</td>
         <td >
               {data.Product_Comp} {data.Product}
               <br></br>
               {findDuplicatesRows(data).map(d => (
                 <tr>{d.Prod_SrNo}</tr>
               ))}
               <br></br>
         </td>
         <td >1</td>
         <td >{data.Price}</td>
         <td >{data.Discount}</td>
         <td >{(data.Price - (data.Price * data.Discount) /100).toFixed(2)}</td>
   </tr>
))}

but you have to calc the total values of the duplicates, for example

calc the total amount

function calcTotalAmount(data){
const amount = (data.Price - (data.Price * data.Discount) /100).toFixed(2);
const quantity = findDuplicatesRows(data).length;
return amount * quantity;
}

<td>{calcTotalAmount(data)}</td>

I think there is a simpler way to do it, but get the fundamental

  • Related