In order to resolve this issue, I must eliminate any duplicate objects and then calculate the total sum using JavaScript

I have successfully removed the duplicates so far, but now I am stuck on how to sum the Total_Quantity. Is there a way to achieve this within the reduced method itself? Any help would be appreciated. Thank you.

const test = [
        {
            Item_Name: "Washing Machine",
            Total_Quantity: 2,
        },
        {
            Item_Name: "Washing Machine",
            Total_Quantity: 2,
        },
        {
            Item_Name: "Washing Machine",
            Total_Quantity: 2,
        },
        {
            Item_Name: "Washing Machine",
            Total_Quantity: 2,
        },
        {
            Item_Name: "Dryer Machine",
            Total_Quantity: 5,
        },
        {
            Item_Name: "Dryer Machine",
            Total_Quantity: 5,
        },
        {
            Item_Name: "Dryer Machine",
            Total_Quantity: 5,
        },
        {
            Item_Name: "Dryer Machine",
            Total_Quantity: 5,
        },
    ];

    const dup = [
                ...test.reduce(
                    (map, obj) => map.set(obj.Item_Name, obj),
                    new Map()
                ).values(),
            ];
    
    console.log(dup)

This is what the code should reflect:

 const dup = [
    {
        Item_Name: "Washing Machine",
        Total_Quantity: 8,
    },

    {
        Item_Name: "Dryer Machine",
        Total_Quantity: 20,
    },
];

Answer №1

this method

const test = 
  [ { Product_Name: 'Toaster', Quantity: 3 } 
  , { Product_Name: 'Microwave', Quantity: 2 } 
  , { Product_Name: 'Blender', Quantity: 1 } 
  , { Product_Name: 'Coffee Maker', Quantity: 4 } 
  , { Product_Name: 'Toaster', Quantity: 3 } 
  , { Product_Name: 'Microwave', Quantity: 2 } 
  , { Product_Name: 'Blender', Quantity: 1 } 
  , { Product_Name: 'Coffee Maker', Quantity: 4 } 
  ] 
const totalQuantity = Object.entries(test.reduce((acc,{Product_Name, Quantity})=>
  {
  acc[Product_Name] = (acc[Product_Name] ?? 0) + Quantity
  return acc
  },{})).map(([Product_Name, Quantity])=>({Product_Name, Total_Quantity}))

console.log( totalQuantity )
.output-console {max-height: 100%!important;top:0;}

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

Several SVG Components failing to function properly or displaying differently than anticipated

I've encountered a puzzling issue that I just can't seem to solve. Here's the scenario: I'm working on a NextJS App and have 5 different SVGs. To utilize them, I created individual Icon components for each: import React from 'reac ...

What is the most effective method for incorporating multi-line breadcrumb links in a React application?

I am currently working on implementing a multiline breadcrumb link feature for mobile and tablet devices. As users navigate through multiple folders, I need to handle scenarios where the number of links exceeds the maximum allowed in the breadcrumb contain ...

The jQuery autocomplete feature seems to be malfunctioning as no suggestions are showing up when

I am currently generating input text using $.each: $.each(results, function (key, value) { if (typeof value.baseOrSchedStartList[i] != 'undefined') { html += "<td><input type='te ...

"Use jQuery to target the first child element within a parent element that has a specific class

Is there a way to choose only the first child of a specific parent class with a certain class for the purpose of clone()? <div class="sector_order"> <div class="line_item_wrapper"> SELECT THIS DIV </div> <div class=" ...

a guide on transforming a string array into JSON

I initialized an array like this String[] finalcodes = new String[50] ; and populated it with some values. However, when I print finalcodes, the output is: ["aaa","bbb","ccc"] My goal is to convert this string array into a JSON Object. Can someone pl ...

Mapping an object in ReactJS: The ultimate guide

When I fetch user information from an API, the data (object) that I receive looks something like this: { "id":"1111", "name":"abcd", "xyz":[ { "a":"a", "b":"b", "c":"c" ...

Parenting and Child Components: Keeping the State in Sync

I am currently diving into my initial React project which focuses on a basic expense tracker for credit cards. While I'm still in the learning phase, I hope you can decipher the intent behind my code. My current roadblock involves mapping the state an ...

Are Viewmodel contents empty after ajax request?

Currently working on an ASP.NET MVC application, I am in the process of developing a search page that showcases both the search box and the table of results simultaneously. To achieve this functionality, I have utilized Partial Views along with AJAX/JSON c ...

Oops! The system encountered a problem while trying to identify the value `Han` for the property `Script

I'm attempting to extract Chinese characters from a string. According to this particular answer, the following code snippet should work: const nonChinese = /[^\p{Script=Han}]/gimu; const text = "asdP asfasf这些年asfagg 我开源的 几 ...

The images in the React slick carousel appear to be slightly out of

I'm experiencing blurriness in my carousel when it animates with card items. Despite searching for a solution, I haven't found one yet. My tech stack includes Next.js and TypeScript. const ref = useRef<any>(); const settings = { arro ...

When the document is fully loaded on a page that has been dynamically loaded

Currently utilizing the following: $("#someDiv").load("ajax.html") The contents of "ajax.html" include a document.ready call: <script>$(function() { alert('works') })</script> I'm interested to know exactly when this callbac ...

nested dropdowns in Bootstrap 4

I'm currently working on a nested dropdown menu feature. Although I have successfully implemented the functionality to display the next level, I am facing an issue where it does not close upon clicking. Check out my code here! Here is the JavaScript ...

How come my date computed property does not update reactively when changes occur?

I have a Date object in my data, and I need to convert the date into a string for a date picker component in Vuetify. The initial date is being read and displayed correctly. I am able to set the date as well - when I set a code breakpoint, I can see the ...

When trying to validate an HTML form using AJAX, jQuery, and JavaScript, the validation may not

Here is a high-level overview of what happens: The following code functions correctly... <div id='showme'></div> <div id='theform'> <form ...> <input required ... <input required ... <inpu ...

Modify the h:outputText value dynamically with the power of jQuery!

Is it possible to use jQuery to dynamically change the value of my OutputText component? This is the code snippet for my component: <h:outputText id="txt_pay_days" value="0" binding="#{Attendance_Calculation.txt_pay_days}"/> I would apprecia ...

contrasting the application of logic in Rails controllers versus JavaScript within the .js.erb files

When dealing with a large "data" active record object that needs to be filtered based on user interactions on a page, the question arises about where to place the data-filtering logic. Currently, the filtering is done in the rails controller action, simpli ...

Empty JSON string is returned when a post request is sent using the codeName "one"

I have been attempting to make a POST request with a JSON BODY in CodeName one. However, when the request reaches the server, the Json String is empty. Below is the code snippet responsible for establishing the connection and sending the message: JSONOb ...

Export data from a JSON object to a CSV file within the Osmosis function

I am currently utilizing Osmosis, a node.js tool, to extract data in the form of an array of JSON objects. The behavior of Osmosis functions indicates that the array is confined within the function's scope. Consequently, I must also write the file in ...

Step-by-step guide on activating a controller function following an Animation in Angular JS

I have hit a roadblock trying to connect a series of animations with a controller action. My goal is to: 1. click on a button/div, 2. Trigger an animation, 3. Once the animation finishes, execute a function in the controller to reset the button/div. I&a ...

Unleashing the potential of Chrome's desktop notifications

After spending the past hour, I finally found out why I am unable to make a call without a click event: window.webkitNotifications.requestPermission(); I am aware that it works with a click event, but is there any way to trigger a Chrome desktop notifica ...