Tips for calculating the total of an array's values

I am seeking a straightforward explanation on how to achieve the following task. I have an array of objects:

const data =
[
    {
        "_id": "63613c9d1298c1c70e4be684",
        "NameFood": "Coca",
        "count": 2
    },
    {
        "_id": "63621f10b61f259b13cafe8e",
        "NameFood": "Xa xi",
        "count": 2,
    },
    {
        "_id": "63654bf94b61091ae9c4bfd3",
        "NameFood": "Cafe đen",
        "count": 2,
    },
    {
        "count": 1,
        "_id": "63613c9d1298c1c70e4be684",
        "NameFood": "Coca",
    }
]

The intended outcome is to filter out duplicate values based on _Id and add up their 'count' values.

const data =
[
    {
        "_id": "63613c9d1298c1c70e4be684",
        "NameFood": "Coca",
        "count": 3
    },
    {
        "_id": "63621f10b61f259b13cafe8e",
        "NameFood": "Xa xi",
        "count": 2,
    },
    {
        "_id": "63654bf94b61091ae9c4bfd3",
        "NameFood": "Cafe đen",
        "count": 2,
    },
]

If anyone could provide a step-by-step explanation, it would be highly appreciated!

Answer №1

One simple way to achieve this is by utilizing the reduce() function

const data =
[
    {
        "_id": "63613c9d1298c1c70e4be684",
        "NameFood": "Coca",
        "count": 2
    },
    {
        "_id": "63621f10b61f259b13cafe8e",
        "NameFood": "Xa xi",
        "count": 2,
    },
    {
        "_id": "63654bf94b61091ae9c4bfd3",
        "NameFood": "Cafe đen",
        "count": 2,
    },
    {
        "count": 1,
        "_id": "63613c9d1298c1c70e4be684",
        "NameFood": "Coca",
    }
]

let result = data.reduce((acc, curr) =>{
  let obj = acc.find(item => item._id === curr._id);
  if(obj){
      obj.count += curr.count;
   }else{
     acc.push(curr);
   }
   return acc;
},[]);
console.log(result)

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

An issue with displaying images has been identified within Next.js, resulting in an error message related to the hostname

Encountering an error when using next js Image next.config.js: module.exports = { images: { domains: ['localhost'], }, }; Error image: https://i.stack.imgur.com/RvsdH.png I am struggling to understand how to correctly set up the image ...

Including a unicode escape sequence in a variable string value

I'm struggling to find the right way to include a unicode escape in a dynamic string value to display emojis in React. My database stores the hexcode for the emoji (1f44d) I have set up a styled-component with the necessary css for rendering an emoj ...

Using JSON Web Tokens for PHP authentication

Currently in the process of developing a 'social network' platform, with emphasis on creating the authentication module. Recently delved into the realm of JSON Web Tokens (JWT). 1) Initial understanding proposed that JWT's offer security du ...

Child component not displaying React props (although I can identify them in debug mode)

Currently, I am working on a React project that does not involve Redux. However, I am encountering some difficulties in passing the state from the parent component to the child component. Despite watching numerous tutorials and extensively using the Chrome ...

Is it possible to utilize the package.json "resolutions" field to replace lodash with lodash-es?

Is it possible to use resolutions in a similar manner as dependencies, but with a different package? I'm specifically curious if this can be done with NPM or Yarn. "resolutions": { "lodash": "npm:lodash-es@^14.7.x" ...

Tips for storing unique values in an object using JavaScript

I need assistance with organizing my log data, which includes camera names and system IP addresses. I am trying to create an object where each unique system IP is a key, with an array of corresponding camera names as the value. Here is the code snippet I h ...

Unable to understand the JSON response object

Struggling to parse a JSON response from FlickR, encountering some difficulties. Despite receiving a response code of 200 and being able to log the actual JSON data, I hit a null pointer error when attempting to access the JSON object. Suspecting an issue ...

Oops! There was an issue with the form field - make sure to include a MatFormFieldControl for proper validation on the

I am working on an Angular application that utilizes Angular Material components. Despite conducting extensive research online, I have not been able to find a suitable solution to the specific error message I have encountered. The issue revolves around a ...

Obtaining Prisma arguments by providing the table name as a string

Is there a way to retrieve the query arguments for a Prisma function by only passing the table name? Currently, I know I can obtain the table by providing the table name as a string in the following manner: function (tablename: string) { await prisma.[tab ...

Synchronizing other components with a filtered query from the List in Admin-on-rest: Best practices

I am looking to incorporate the following structure into my page: 1. Cards displaying summaries (revenue, users, etc.) 2. Google Maps integration 3. List element Within the List element, there is filtering involved. I am struggling with how to utili ...

Utilizing jQuery BBQ for Seamless Transitions – From Fading to Sliding and More

This is my first time posting a question here, even though I am an active user of stackoverflow. I have developed a website using jQuery BBQ to load pages through AJAX while still maintaining the ability to track history with the back button and other fun ...

Implementing new Datatables 1.10 parameters for model binding

There have been changes in the ajax server side parameters for Datatables 1.10. The previous model looked like: public class DataTableParamModel { public string sEcho{ get; set; } public string sSearch{ get; set; } public int iDisplayLength{ ...

Steps to store chosen option from dropdown list into a database's table

I am currently populating a dropdown list in my PHP file by fetching data from a database. Here is the code snippet: <script type="text/JavaScript"> //get a reference to the select element var $select = $('#bananas'); //reques ...

What method can I use to modify the object's keys based on certain conditions in ES6/React?

How can I dynamically change the value of an object's keys based on specific conditions? What is the most effective way to structure and implement this logic? Data const newData = { id: 111, name: "ewfwef", description: "Hello&qu ...

Is it possible to utilize a map in Python or incorporate other advanced functions to efficiently manage indices?

When working with higher order functions in JavaScript, we have the ability to access the element, index, and iterable that the function is being performed on. An example of this would be: [10,20,30].map(function(element, index, array) { return elem + 2 ...

Creating two separate divs that can scroll independently while also limiting each other's scroll depth can be achieved by utilizing

I am attempting to replicate the unique scrolling feature seen on this particular page. Essentially, there are two columns above the fold that can be scrolled independently, but I want their scroll depths to be linked. When a certain depth is reached whil ...

Utilizing `v-model` on a component that contains `<script setup>` in Nuxt can cause issues with the standard `<script>` tags

Working on a Nuxt3 project, I have implemented v-model on a component. Following the guidance from Vue documentation, here is how it should be done: In the parent component: <MyInput v-model="myData" placeholder="My placeholder" /&g ...

Creating a Three.js 3D Text Effect with Layers of Letters

Why are my 3D text letters overlapping in the threejs TextGeometry when viewed from an angle? https://i.sstatic.net/W0ocu.png See the code snippet below: class MyScene { // Code for handling Three.js scene and elements constructor(elementSelector ...

Utilizing jQuery to send AJAX requests and display the results on separate lines within a textarea

My form includes a text area where users can enter keywords, one per line. I would like to implement the following functionality: upon clicking a button, an ajax request will be sent to the server to retrieve the result for each keyword entered. The resul ...

What is the best way to initiate a change event using JavaScript?

I am attempting to enable my 4th checkbox automatically when there is a new value in the textbox (myinput). If the textbox is empty, I want to disable it. Currently, you have to tab out before the change event is triggered. Also, how can I check for an e ...