Merge identical data into a unified field within a table

I have a table that displays different colors and their quantities. I would like to merge rows with the same color into one row, with the total quantity shown in that row.

For instance, if there are 2 "black" colors with quantities of 5 and 2, I want to combine these two rows into one with the quantity field showing "5+2 = 7".

Here is an example of what I am looking for:

th{
border:1px solid black;
}
<table>
<thead>
<tr>
<th>Color</th>
<th>Rate</th>
<th>Qty</th>

</tr>
</thead>
<tbody>
<tr>
<td>white</td>
<td>1</td>
<td>0</td>
</tr>

<tr>
<td>Black</td>
<td>5</td>
<td>7</td>
</tr>
<tr>
<td>red</td>
<td>6</td>
<td>0</td>
</tr>

</tbody>
</table>

Answer №1

To achieve this task with ease, you can utilize a single pass through the data using JavaScript's reduce() method instead of resorting to multiple loops.

const information = { categories: [{ "selectedCategory": "clothing", "selectedPrice": 30, "isSelected": true }, { "selectedCategory": "electronics", "selectedPrice": 50, "isSelected": false }, { "selectedCategory": "books", "selectedPrice": 20, "isSelected": true } ]};

const totalResult = information.categories.reduce((acc, {
    selectedCategory: sc,
    selectedPrice: sp,
    isSelected: si
}) => {

    if (acc[sc]) return {
        ...acc,
        [sc]: {
            selectedCategory: sc,
            selectedPrice: acc[sc].selectedPrice + parseInt(sp),
            isSelected: acc[sc].isSelected && si
        }
    }

    return {
        ...acc,
        [sc]: {
            selectedCategory: sc,
            selectedPrice: parseInt(sp),
            isSelected: si
        }
    }

}, {});

console.log(Object.values(totalResult));

Answer №2

If you want to optimize your code, consider creating a computed method to generate a new array. Instead of directly accessing the data in your v-for loop, utilize the computed property.

You can see an example implementation in this CodePen: https://codepen.io/ValentinM27/pen/GRGvmMp?editors=1011

Below is the key segment of the code:

...
computed: {
      getGrouped() {
        let groupedItems = [];
        this.items.forEach((item, index) => {
          // Check if the item has been processed before
          const exists = groupedItems.some(i => i.id === item.id);
          
          // Avoid duplicate processing
          if(exists) return;
          
          this.items.forEach((item2, index2) => {
            // Process items with matching criteria but different indexes
            if(item.criteria === item2.criteria && index !== index2) {
              item.value = parseInt(item.value) + parseInt(item2.value);
            }
          })
          
          // Add the aggregated item to the result array
          groupedItems.push(item);
        })
        
        // Return the final array with aggregated values
        return groupedItems;
      }
   },
...

Update your template as follows:

...
<div v-for="(item, i) in getGrouped" :key="i">
...

Hope this solution meets your requirements!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Develop universal filter functions that each interact with a shared API and implement them across various components within a VUE.js application

I am facing a dilemma regarding global filter functions that utilize the same API for filtering. I am unsure of how to achieve this effectively. To provide clarity, here is an example: Using vuex getters, I am passing data to my list and map components on ...

What is the best way to invoke a Rest API within a Vue component?

As a newcomer to VueJS, my goal is to create a basic page featuring a pie chart displaying some data. Currently, I have successfully displayed the chart using example data. However, I now wish to populate the chart with data fetched from an API call on my ...

Tips for assigning unique names to each radio input groupNeed to assign unique names to radio

Currently, I am seeking a dynamic solution to alter the name associated with a set of radio input buttons. The situation involves creating a travel itinerary where users can choose between "domestic" and "international." Based on this selection, the corre ...

Calculating the position of an element in an array passed from a separate file with ReactJS and Ant Design

I'm currently working with a file that contains some JavaScript code featuring an array with multiple objects containing key-value pairs. In my main file (App.jsx), I initialize a State Variable and assign it the array from another JS file. My goal no ...

Troubleshooting: AngularJS - Issues with nested controllers not functioning properly within ng-include

According to the AngularJS documentation (refer to nested controller fragment), I am attempting to implement nested controllers using ng-include Main.html <body id="spaWrapperApp" ng-app="spaWrapperApp"> <div class="container-fluid" id=" ...

Tips for passing a state value to a different state when initializing in react js

I need some help with passing a state value called imagesArray to another state named tabData. It seems like the value is coming up as undefined. Below is the code snippet, can you please point out what I might be doing wrong? constructor(props) { s ...

The Vue application is unable to expand to 100% height when using a media query

Hello everyone, I'm currently using my Vue router for multiple pages, and I'm facing an issue where setting the height of the main container to 100% within this media query is not working as expected: @media screen and (min-width: 700px) { #sig ...

The journey of data starting from a PHP file, moving through JavaScript, and circling back to PHP

I've encountered an interesting challenge with my PHP file and Wordpress shortcode. It all starts when the shortcode is embedded in a webpage, triggering a php function from within the file. This function executes an SQL query to extract data, then s ...

Unable to bring in openai on Node.js

I recently installed Node version 16.13.1 and globally installed the openai package using 'npm install -g openai'. In my script, I imported the necessary packages like this: const { Configuration, OpenAIApi } = require('openai') Howeve ...

The proper method to retrieve the parent function parameter within an inner JavaScript callback function

Consider the code snippet below. var exec = require('child_process').exec; var extraInfo = {'test':1,'passing':'test'}; runWithData(extraInfo); function runWithData(passedData) { exec('/Users/test/Deskto ...

The Navigation Bar in Vue Component Renders Incorrectly due to Bootstrap Integration

I am facing an issue with my Bootstrap navbar not displaying correctly within my Vue component. It is appearing as a stacked greyed out button, almost like it's assuming it's on a small device. https://i.sstatic.net/yoPvO.png You can find the c ...

Problem arising from apostrophe usage in Javascript OData request

In my current project, I have a text input field that passes a value through JS to fetch filtered data of names from a JSON file using OData query parameters. However, I've encountered an issue where if a name contains an apostrophe, it results in a ...

What is the best way to display a loading image and temporarily disable a button for 3 seconds before initiating the process of sending post data from another page via

Is there a way to display a loading image and disable a button for 3 seconds before sending post data from another page using AJAX POST? Once the OK button is clicked, I would like the loading image to appear and the <input type="button" value="Check" ...

Is it possible to manage the form submission in React after being redirected by the server, along with receiving data

After the React front-end submits a form with a POST request to the backend, the server responds with a JSON object that contains HTML instead of redirecting as expected. How can I properly redirect the user to the page received from the server? For inst ...

Is the jqm flipswitch with the label on the left and the switch on the right?

My goal is to display multiple flipswitches on a mobile app page. This is the code I am using: <div class="ui-content"> <form> <fieldset> <div data-role="fieldcontain"> <label for="checkbox-based-flipswitch" ...

Generating new elements on the fly using jQuery and passing a string parameter through the onclick event

While dynamically creating HTML, I encountered a syntax error. If I modify href="javascript:startChat(' + user_id + ','video')" to href="javascript:startChat(' + user_id + ','"video"')", I receive an error stating &a ...

Is it possible to dynamically group by one column in a dataset without requiring a trigger function?

I've been working on a script that retrieves values from another page and organizes them into a table alphabetically by Name, City, and District. The current script is functioning well, but I now want to enhance it by grouping the values by city as we ...

Summing up numbers within a hierarchical table using jQuery

There are two tables, each with their own unique ID as shown below: <table id="cvo"> <tr id="1"> <td>C</td> </tr> <tr id="2"> <td>C</td> </tr> <tr id="3"> <td>O</ ...

Updating the JSON format output from snake case to camel case in a React web application

Modifying JSON output in a React Web app to change keys from snake case to camel case Currently, the API endpoint response is structured like this: [ { "id": 1, "goals_for": 0, "goals_against": 0, "points": 0 } ] ...

Subscribe on Footer triggers automatic scrolling to the bottom of the page

Whenever I fill out the form in the footer and hit submit, it directs me to a different page while automatically scrolling back down to the footer. I'm looking for a solution that prevents this automatic scrolling. I've attempted using window.sc ...