Is there a way to combine two objects within an array and calculate the sum of their elements?

Can anyone suggest a method to merge objects and calculate the total number of their elements simultaneously? I'm struggling to find a way to combine them while also adding up the chats count.

Here is an example array:

  [
   [
    {
      id: 'call_000001',
      date: 2019-04-01T00:00:00.000Z,
      chats: 121,
      missedChats: 0
    },
    {
      id: 'call_000001',
      date: 2019-04-02T00:00:00.000Z,
      chats: 92,
      missedChats: 1
    }
  ],
  [
    {
      id: 'call_000002',
      date: 2019-04-01T00:00:00.000Z,
      chats: 13,
      missedChats: 0
    },
    {
      id: 'call_000002',
      date: 2019-04-02T00:00:00.000Z,
      chats: 12,
      missedChats: 3
    }
  ],
  ]

This is the desired result:

[
 {
  id: 'call_000001',
  chats: 213,
  missedChats: 1,
 },
 {
  id: 'call_000002',
  chats: 25,
  missedChats: 3,
 },
]

Could someone provide guidance on the most effective approach to achieve this without relying on underscore or lodash?

Answer №1

Check out this code snippet:

info = [
  [{
      id: 'call_000001',
      date: '2019-04-01T00:00:00.000Z',
      chats: 121,
      missedChats: 0
    },
    {
      id: 'call_000001',
      date: '2019-04-02T00:00:00.000Z',
      chats: 92,
      missedChats: 1
    }
  ],
  [{
      id: 'call_000002',
      date: '2019-04-01T00:00:00.000Z',
      chats: 13,
      missedChats: 0
    },
    {
      id: 'call_000002',
      date: '2019-04-02T00:00:00.000Z',
      chats: 12,
      missedChats: 3
    }
  ]
]


var combinedInfo = info.map(infoElement => infoElement.reduce((accumulator, element) => {
  return {
    id: accumulator.id,
    chats: accumulator.chats + element.chats,
    missedChats: accumulator.missedChats + element.missedChats
  }
}));


console.log(combinedInfo);

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

In C, what do you do when the case label cannot be reduced to an integer constant?

I've encountered an error while working on my game that says "case label does not reduce to an integer constant." I have an idea of what might be causing this, but I'm not sure how to resolve it. Below is the snippet of code where the issue arise ...

A C# program that creates an array collater where the value of every other element is the same throughout the

I'm currently exploring an extension of my project, looking for a more concise solution. While it's easy to achieve this in a loop, I am curious if there is a way to do it in just one line of code. Here is the initial input: byte[] x = new byte ...

How can I transfer a JavaScript variable to a Django template before submitting the form?

Trying to fetch a selected approver and validate before submitting a form in Django has proven quite complex. I've made significant progress, but I'm stuck on figuring out how to "get" the translated ID in the Django template. I have the ID, but ...

Invoke a function from within an event handler

Is there a way to trigger a function once an event has been completed? For example - $('.class').slideUp('fast', function() { // execute the function }); ...

Utilizing ES6 default arguments for managing empty strings

Here is a simple key-value map of colors based on types: const COLORS_BY_TYPE = { RED: 'red', BLUE: 'blue', GREEN: 'green', }; const getCorrectColor = ({ colorType = 'GREEN' }) => COLORS_BY_TYPE[colorType. ...

Implementing a JavaScript Module Using JavaScript

I have encountered a simple problem. I am trying to use two JavaScript files: one following the module pattern and another one that calls the first one. I have tested all the code using Node.js and everything works fine when it is all in one file. However, ...

Searching for the closest array using C++

For my assignment, I am required to create an array with 5 random values, prompt the user to input a number for searching, and then display the index of the searched number. While this task seems relatively straightforward (and I have managed to do it), no ...

When utilizing bootstrap, encasing an input text element in a label results in the text becoming bold and not occupying the entire width

I have been experimenting with wrapping my text input fields in labels. While this technique works well with pickers on my form, it seems to cause issues when applied to text boxes. If I choose not to wrap the text boxes, the alignment between the label an ...

Am I following the right approach for implementing Dependency Injection in Node.js?

Recently embarking on a new node project, I encountered a dependency injection issue with my fresh module as a Test-Driven Developer. Here's how I resolved the problem using an approach that involves vows for BDD testing and Sinon. The module in ques ...

Is it possible for you to execute 2 procedures consecutively simply by clicking on a button?

My question is quite straightforward. I have two buttons: <button @click="getPartyLeader" class="btn btn-success">Get party leader</button> <button @click="saveParty" class="btn btn-success">Submi ...

What is the best method for transforming a JavaScript array of Objects to a different format?

Is there a way to transform this array of objects from one format to another? The original array is as follows: const data = [ {name: 'Customer 1', value: {Oil: 55, Gas: 66, Retail: 56}}, {name: 'Customer 2', value: {Oil: ...

Issue with Ajax request not adding content to div

My issue with ajax $('#searchform').submit(function(event) { $.ajax({ type: "get", url: "/list", dataType: "text", data: $("#searchform").serialize(), beforeSend: function() { $(".se-pre-con").show(); }, ...

Concentrate on all elements within the form

I am in the process of developing a form with multiple input fields, one of which is shown below. I am interested in triggering an event using jQuery's focusout function. The form goes by the name: form_test <form id="form_test"> <input ...

Develop an array of unique objects with multiple dimensions, ensuring no duplicates are included

Seeking assistance for the following task: I am trying to create a new multidimensional array of objects based on an existing array of objects: [ {number:111, connectedNumber: 112, ...}, {number:112, connectedNumber: 111, ...}, {number:113, connectedNumbe ...

Is it possible to customize Ag-grid checkboxes depending on the data in each column?

import React, { Component } from 'react'; import ReactHighcharts from 'react-highcharts'; import axios from 'axios; import { Link, browserHistory } from 'react-router'; import { AgGridReact, AgGridColumn } ...

Transform JSON data into an array using the nlohmann/json library

It's been more than two decades since I last delved into C++, so my skills are a bit rusty in this area. Currently, I am utilizing the nlohmann/json json.h library and facing the challenge of converting a JSON string that represents an array of objec ...

Utilizing Typescript: Bringing in a module that was exported using module.exports

I am facing an issue with a theme file that needs to be written in ES5: module.exports.theme = { primaryColor: 'blue', borderSize: '2px', // ... } In my attempt to import this theme file in a Typescript file within a c ...

Inline editing in Kendo UI that allows for dynamic editor changes

Hey there! I've been working on a project with two columns, and here's a demo link for reference. In the first column, we have "Setting Type," which includes a drop-down list. The second column is the "Editor," which contains the value of the r ...

The function queryDatabases is not supported in the DocumentDB JavaScript API

Currently, I am developing a service for Azure Functions using JavaScript/Node.js. However, I encounter an error when trying to access the function DocumentClient.queryDatabases. Despite having the correct references installed in Visual Studio Code and bei ...

What is the best way to refresh the innerHTML of a div using the values from a JavaScript array when new elements are added to it?

I currently have an array with three items, along with four buttons - each designed to add a new item to the array. Although the process of adding items into the array using the buttons is successful, I am facing an issue with the display within the div e ...