Performing array reduction and summation on objects in JavaScript

Data Analysis:

dataSet: [],
models: [
    { id: 1, name: "samsung", seller_id: 1, count: 56 },
    { id: 1, name: "samsung", seller_id: 2, count: 68 },
    { id: 2, name: "nokia", seller_id: 2, count: 45 },
    { id: 2, name: "nokia", seller_id: 3, count: 49 }
]

Desired Output:

dataSet: [
    { id: 1, name: "samsung", count: 124 },
    { id: 2, name: "nokia", count: 94 }
]

This script aims to simplify the data set by removing duplicate ids:

this.models.forEach(mdl => {
    if (!this.dataSet.some(obj => obj.id === mdl.id)) {
        this.dataSet.push(mdl);
    }
});

However, the challenge lies in summing up the count values.
Any suggestions on how to achieve this?

Answer №1

You have the option to utilize Array.reduce():

var mobiles = [
    { id: 1, name: "samsung", seller_id: 1, count: 56 },
    { id: 1, name: "samsung", seller_id: 2, count: 68 },
    { id: 2, name: "nokia", seller_id: 2, count: 45 },
    { id: 2, name: "nokia", seller_id: 3, count: 49 }
];

var phones = mobiles.reduce((acc, item) => {
  let existingItem = acc.find(({id}) => item.id === id);
  if(existingItem) {
    existingItem.count += item.count;
  } else {
    acc.push(item);
  }
  return acc;
}, []);

console.log(phones);

Therefore, in your code, you can replace variables with this.arr and this.mobiles, updating them accordingly:

this.arr = this.mobiles.reduce((acc, item) => {
  let existingItem = acc.find(({id}) => item.id === id);
  if(existingItem) {
    existingItem.count += item.count;
  } else {
    acc.push(item);
  }
  return acc;
}, []);

Answer №2

To replace the usage of some, you can opt for Object.values. In the reduce function, construct an object with the key as id and values from the models. Afterwards, employ Object.values to generate an array consisting of these values.

let models = [{
    id: 1,
    name: "samsung",
    seller_id: 1,
    count: 56
  },
  {
    id: 1,
    name: "samsung",
    seller_id: 2,
    count: 68
  },
  {
    id: 2,
    name: "nokia",
    seller_id: 2,
    count: 45
  },
  {
    id: 2,
    name: "nokia",
    seller_id: 3,
    count: 49
  }
]
let data = models.reduce((acc, curr) => {
  if (!acc[curr.id]) {
    acc[curr.id] = curr;
  } else {
    acc[curr.id].count += curr.count

  }
  return acc;
}, {})
console.log(Object.values(data))

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

Deactivating elements on a website

Is there a way to prevent multiple transactions due to unintended repeated clicks on a button by disabling all webpage elements when the button is clicked? Suggestions include using a div that can be layered on top of the elements when the button is click ...

The v-bind class feature is failing to update the CSS on the object's properties

I'm attempting to dynamically modify the CSS of certain buttons based on object properties within a list. Below is the data I am rendering out, and despite following the documentation and ensuring my setup is correct, I seem to be overlooking somethin ...

Timepicker.js - Incorrect Placement of Time Picker in Certain Scenarios

Utilizing the timepicker.js library to select a time, I am encountering an issue. When clicking on the input field, the timepicker should appear next to it. This function works as expected when the input is within the main view of the document. However, if ...

how to execute a javascript function in an ionic controller from the template

My journey in creating my first Ionic app has been smooth so far. I am not well-versed in UI design, so I may not be implementing the best practices, but I am making progress nonetheless... Within a template, I have encountered the following code snippet ...

javascript Click to add a tag

I am currently using a rich text editor and I'm attempting to add a code tag feature to it. Currently, the editor has two buttons - one for underline and one for code. When I select text and click the underline button, the selected text will be under ...

Setting the current date as the default in an input box using ng-it: a step-by-step guide

How do I automatically set today's date as the default in the input box using ng-it? Here is my Plunker I am simply looking to set today's date as the default in the input field using ng-it. Would appreciate it if you could check out my P ...

Populate array with values using foreach loop

Struggling to populate an array using foreach, it's only displaying the word "Array" instead of the expected strings. $msg = array(); foreach ($results as $result) { $inventory = $result->qoh; $inventoryOrder = $result->qo; $pro ...

Exploring Techniques for Adjusting Website to User's Screen Resolution

My website is currently designed for a screen resolution of 1024x768. However, I am aware that when viewed on computers with smaller or larger screen resolutions, the layout starts to distort. Is there a way to make the website adaptable to any user&apos ...

Dynamic properties in JQuery

Here is the HTML DOM element I have... <input type="text" style="width: 200px;" id="input1"/> I want to make sure it stores date values. How can I specify that in the DOM element? Please provide your suggestions. Thanks! ...

What is the best way to generate a complete PDF of a webpage using pdfmake?

I'm currently developing a web application and facing the task of converting an HTML page, which contains multiple tables and datatables, to a PDF format. To achieve this, I've chosen to utilize the library pdfmake. Below is the script that I ha ...

Expanding the size of a Three.js geometry in one direction

I've been experimenting with scaling geometries on the y-axis, but I've run into an issue where my cube scales both up and down. I found that using mesh.transformY to animate the cube up by half of the scaling value can create the illusion of the ...

Adding child arrays to a parent array in Angular 8 using push method

Upon filtering the data, the response obtained inside the findChildrens function is as follows: My expectation now is that if the object length of this.newRegion is greater than 1, then merge the children of the second object into the parent object's ...

Does the Apps Script parser JSON.parse() incorrectly remove leading zeros from string object keys?

I am facing an issue with my Apps Script Web App where JSON data is being manipulated when I try to parse it. Specifically, keys with leading zeros are being altered (e.g "0123" becomes "123") during the JSON.parse() function call. It seems like the functi ...

What do I need to add in order to connect a controller to a form submission?

Let's set the scene: There are multiple newsletter forms scattered across a webpage, all needing to perform the same action. This action involves making an AJAX request with certain data and displaying a message using an alert once the request is comp ...

Issue with React Native Hook where converting a function into a class variable results in 'undefined'

We are currently in the process of converting a react native function into a class so that we can implement state management compatible with Firebase's real-time database. It recently came to our attention that Hooks cannot be used within a class, so ...

Text in d3.js vanishing while undergoing rotation

I have been struggling for hours with what seems like a simple problem and haven't made any progress. I'm hoping to receive some valuable advice from the brilliant minds on stackoverflow. You can view my demo at I attempted to use jsfiddle to s ...

Displaying directory contents with JavaScript XHR

When I inquired whether javascript has the ability to list files on the server, the general response was that "javascript cannot access the server filesystem since it is a client-side scripting language". However, I believed this answer was only partially ...

React - Utilizing Secondary Prop Value in Material UI Node Components

I've been working on streamlining my code and am wondering about the best way to pass an additional value using props while fetching data from the backend. I'm utilizing material UI's Autocomplete with the PERN stack. Everything is functioni ...

Rendering the Next.js Link tag on the page is displaying as [object Object]

Hey there! I'm currently working on creating breadcrumbs for a webpage and this is what the breadcrumb array looks like: const breadcrumbs = ['Home', "Men's Top", 'Winter Jacket'] Now, in JSX with Next.js, I am att ...

Tips for sending a form as a PDF attachment through email using Nodemailer, React, and Node.js

Imagine a scenario with a React form. Here's what I envision: fill out the form, click the submit button, and watch as the form magically generates a PDF that gets sent as an attachment via Nodemailer. Sure, I've successfully managed to send emai ...