Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

javascript - Merge 2 table data and add/combine two integer fields

I have a table of data that shows particular product and the amount purchased throughout the day. They were inserted as different objects and I want to add the number of items purchased of each product.

My table look like this

Apple 10 01/20/2021 18:30
Apple 5  01/29/2021 04:30
Apple 20 01/29/2021 07:30

But I want them to be combined into like

Apple 35

So far this is how I set the table

<Table striped="true" size="sm" style={{width: "20%"}}>
 <tbody>
  {this.state.products?.map((product, index) => (
   <tr key={`entity-${index}`}>
     <td>{product.type}</td>
     <td>{product.amount}</td>                        
   </tr>
  ))}
 </tbody>
</Table>

How can I combine those data based on their type?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Below are the steps that I took to solve the problem mentioned above. I have left the usage of state to you to implement it as per your requirement.

  1. First I created an array of fruits and their corresponding quantity purchased
  2. Created a Set to get unique fruits
  3. In the JSX, I have looped over the Set and then calculated the total quantity of those fruits by filtering the fruit name first and then adding the quantity together using reduce
  4. These values were finally displayed in the table

class Fruits extends Component {
  render() {
    const purchasedItems = [
      { fruit: "apple", quantity: 5 },
      { fruit: "apple", quantity: 2 },
      { fruit: "apple", quantity: 10 },
      { fruit: "mango", quantity: 5 },
      { fruit: "mango", quantity: 8 },
    ];

    let uniqueFruit = [...new Set(purchasedItems.map((x) => x.fruit))];
    
    return (
      <div>
        <table>
          <tbody>
            {uniqueFruit.map((fruit_name) => {
              let total = purchasedItems
                .filter((item) => 
                  item.fruit === fruit_name
                )
                .reduce((acc, curr) => acc + curr.quantity, 0);
              return(
              <tr>
                <td>{fruit_name}</td>
                <td>{total}</td>
              </tr>)
            })}
          </tbody>
        </table>
      </div>
    );
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...