What is the best way to deduct specific values from two arrays of objects?

Here I am, being a little silly by posing a not-so-simple question that has been nagging me for quite some time. Let's dive into the data:


    const demo1 = [
       { count: 156, monthCount: 1, year: 2018 },
       {  count: 165, monthCount: 2, year: 2018 },
       {  count: 103, monthCount: 3, year: 2018 },
       {  count: 60, monthCount: 4, year: 2018 }
    ]
    const data2 = [
      { count: 100, monthCount: 1, year: 2019 },
      {  count: 55, monthCount: 2, year: 2019 },
      {  count: 99, monthCount: 3, year: 2019 },
      {  count: 130, monthCount: 4, year: 2019 }
    ] 

My quest is to acquire data3 which equals data2 - data1, with key attributes. The expected output should look something like this:

[
    {count: 56, monthCount: 1 },
    {count: 100, monthCount: 2 },
    {count: 60, monthCount: 3 },
    {count: 70, monthCount: 4 }
]

Answer №1

To achieve the subtraction of data2 - data1, you can utilize vanilla JavaScript for this operation. Here is an illustration along with your provided data:

const data1 = [
  { count: 156, monthCount: 1, year: 2018 },
  { count: 165, monthCount: 2, year: 2018 },
  { count: 103, monthCount: 3, year: 2018 },
  { count: 60, monthCount: 4, year: 2018 }
];
const data2 = [
 { count: 100, monthCount: 1, year: 2019 },
 { count: 55, monthCount: 2, year: 2019 },
 { count: 99, monthCount: 3, year: 2019 },
 { count: 130, monthCount: 4, year: 2019 }
];

Here is an example:

const combined = data1.concat(data2);
console.log(`combined, not calculated`, combined);

const desired = [...combined.reduce((r, {monthCount, count}) => {
const key = monthCount;

  const item = r.get(key) || Object.assign({}, {
    count: 0,
    monthCount: monthCount
  });

  if (item.count === 0)
    item.count = -count;
  else
    item.count += +count;

  return r.set(key, item);
}, new Map).values()];

console.log(`desired: `, desired)

OUTPUT:

[
    {count: -56, monthCount: 1},
    {count: -110, monthCount: 2},
    {count: -4, monthCount: 3},
    {count: 70, monthCount: 4},
]

Answer №2

const data1 = [
       { count: 156, monthCount: 1, year: 2018 },
       {  count: 165, monthCount: 2, year: 2018 },
       {  count: 103, monthCount: 3, year: 2018 },
       {  count: 60, monthCount: 4, year: 2018 }
    ]
  const data2 = [
    { count: 100, monthCount: 1, year: 2019 },
    {  count: 55, monthCount: 2, year: 2019 },
    {  count: 99, monthCount: 3, year: 2019 },
    {  count: 130, monthCount: 4, year: 2019 }
  ];

const subtractData = (arrOne, arrTwo) => {
  const newArr = []
  arrOne.forEach((elOne) => {
    arrTwo.forEach((elTwo) => {
      if(elOne.monthCount === elTwo.monthCount){
        const count = Math.abs(Number(elOne.count) - Number(elTwo.count));
        const newObj = {
         ...elOne,
         count
        }
        delete newObj.year;
        newArr.push(newObj)
      }
    })
  })

  return newArr;
}

console.log(subtractData(data1, data2))

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

Error message: `Socket.io-client - Invalid TypeError: Expected a function for socket_io_client_1.default`

I have successfully installed socket.io-client in my Angular 5.2 application, but after trying to connect (which has worked flawlessly in the past), I am encountering a strange error. TypeError: socket_io_client_1.default is not a function at new Auth ...

How can I utilize the Facebook API on Tizen to share a video?

Could someone please provide guidance on how to incorporate video uploading functionality into a Tizen application using the Facebook API and HTML5? ...

What is the best approach to adding components dynamically in AngularJS?

Can someone explain how to create a component in a controller? I already have an AngularJS module with a controller defined: let app = angular.module('testApp', []); However, when I try to load the component, it does not work as expected. app ...

Leveraging AngularJS, optimizing SEO, and hosting S3 static pages

My web application utilizes AngularJS for the front-end and .NET for the back-end. Within my application, there is a list view. When each item on the list is clicked, it retrieves a pre-rendered HTML page from an S3 bucket. I am implementing Angular stat ...

Refresh information once another user enters data

I'm curious about the most effective method for retrieving data when another user inserts it automatically, without requiring a page refresh. Using socket may not be the best solution since all online users would likely be in the same socket connectio ...

Tips on harnessing the power of AngularJS $scope

In need of assistance! I have a paragraph and a counter that I want to update whenever the user clicks on the paragraph, all using AngularJS. Below is the code snippet I've come up with: <!DOCTYPE html> <html> <head> <script src= ...

Show or hide a fixed position div using jQuery when clicked

I am new to jQuery and I am trying to create a "full page menu" on my own. However, I am struggling to hide the menu on the second click. I tried using .toggle() but I found out that it has been deprecated. Can someone assist me with this? Thank you so muc ...

Identifying the Click Event Within an ngx Bootstrap Modal

I recently set up an ngx bootstrap modal using the instructions provided in this helpful guide - . However, I'm facing a challenge in detecting click events within the modal body once it's open. Below is the code snippet from my app component. D ...

Tips on converting mysql results to JSON using PHP

mysql database table structure: ID >> Name >> Salary The variable $row_set holds information from the database table. However, when using: json_encode($row_set); The output is in this format: [{"0":"1","ID":"1","1":"x","Name":"x","2":"123 ...

Steps to configure a folder as a "module" for importing multiple JavaScript files in bulk

Just as we would import React in a typical way, like this: import * as React from 'react'; and then use it for state management, such as: const [state, setState] = React.useState(false); I have a requirement to import multiple components from a ...

What could be causing the browser to become unresponsive when making several AJAX requests to the same ASP.NET MVC action at once?

The other day, I posed this query: Why is $.getJSON() causing the browser to block? I initiated six jQuery async ajax requests simultaneously on the same controller action. Each request takes around 10 seconds to complete. Upon tracking and logging re ...

"Exploring the Power of ZF2 with Restful APIs and Image

I am currently in the process of developing a website utilizing Zend Framework 2 in combination with AngularJS. The backend consists of a restful webservice running on ZF2, while AngularJS is used on the client side to interact with this webservice. My ne ...

LiveValidation plugin causing issue with removing dynamically inserted elements

My form validation is powered by the Live Validation plugin. After submission, the plugin automatically inserts a line of code like this one: <span class=" LV_validation_message LV_valid">Ok</span> However, I encountered an issue when trying ...

Issue with 'firebase.auth is not defined' error following SDK update

I've been using the Firebase JS sdk for web development without any issues for a year now. However, after recently updating my code from version 5.3.1 to the latest 6.5.0 SDK version, I encountered the following error: TypeError: firebase.auth is no ...

"Utilize PHP to access an object's properties in a manner similar to an array

Consider the JSON object presented below: $json = '{ "Name": "Peter", "countries": { "France": { "A": "1", "B": "2" }, "Germany": { "A": "10", "B": "20" }, .... } }'; I am looking for a way to ...

Calculate the date difference in Nuxt by leveraging the @nuxtjs/moment module

I'm a Nuxt newbie facing an issue with calculating the difference between two dates (user input date and current date). The code I am using works fine in most cases, but when the input date is '2020-03-31' or '2020-01-30', the cons ...

Vue looping through nested checkbox groups

Here is an object I am working with: rightGroups: [ { name: "Admin Rights", id: 1, rights: [ { caption: 'Manage Rights', name: 'reports', ...

Error: Unable to execute $(...).stellar since it is not a recognized function

Having some trouble implementing the stellar plugin. I've included all the necessary js, but keep getting an error in the dev tools console: 'Uncaught TypeError: $(...).stellar is not a function'. Here's what I have in the head tags: ...

Node React authentication

Struggling with implementing authentication in React Router. I am using componentDidMount to check if the user is logged in by calling an endpoint. If not, it should redirect to login, otherwise proceed to the desired component. However, this setup doesn&a ...

Guide to accessing data from dot net core in React Native

Screenshot of Postman showing dot net core API Although Postman successfully fetches data from my dot net core API, I am encountering difficulties in retrieving the data in React Native using the same API. I have tried various solutions, including changin ...