Calculate the total sum of a specific property within an array using ES6

My goal is to calculate the total unit value by date and create a new array without duplicate dates. For instance, I want to sum up the values of 2015-12-04 00:01:00. This particular date appears twice in the dataset with values of 5 and 6, resulting in:

[{date: '2015-12-04 00:01:00', unit: 11}, ... etc]

I attempted to use

arr = results.map(x => x.unit).reduce((a,c) => a + c)
but it only returns a single value instead of an array.

results = [ { unit: 5, date: '2015-12-04 00:01:00' },
          { unit: 10, date: '2015-12-04 00:01:00' },
          { unit: 5, date: '2015-12-04 00:31:00' },
          { unit: 9, date: '2015-12-04 00:31:00' },
          { unit: 5, date: '2015-12-04 01:01:00' },
          { unit: 10, date: '2015-12-04 01:01:00' },
          { unit: 10, date: '2015-12-04 01:31:00' },
          { unit: 5, date: '2015-12-04 01:31:00' },
          { unit: 10, date: '2015-12-04 02:01:00' },
          { unit: 5, date: '2015-12-04 02:01:00' },
          { unit: 5, date: '2015-12-04 02:31:00' },
          { unit: 9, date: '2015-12-04 02:31:00' },
          { unit: 5, date: '2015-12-04 03:01:00' },
          { unit: 9, date: '2015-12-04 03:01:00' },
          { unit: 5, date: '2015-12-04 03:31:00' },
          { unit: 10, date: '2015-12-04 03:31:00' },
          { unit: 10, date: '2015-12-04 04:01:00' },
          { unit: 5, date: '2015-12-04 04:01:00' }];

arr = results.map(x => x.unit).reduce((a,c) => a + c);
console.log(arr);

Answer №1

You can simplify your data by converting it into a dictionary and then transforming it into an array as shown below:

records = [ { unit: 5, date: '2015-12-04 00:01:00' },
      { unit: 10, date: '2015-12-04 00:01:00' },
      { unit: 5, date: '2015-12-04 00:31:00' },
      { unit: 9, date: '2015-12-04 00:31:00' },
      <!-- more records here -->
    ]

// Create an object with key-value pairs of {date: unit}
const simplifiedRecords = records.reduce((acc, item) => ({
  ...acc,
  [item.date]: (acc[item.date] || 0) + item.unit
}) , {})

console.log(simplifiedRecords)
/*
{
  "2015-12-04 00:01:00": 15,
  "2015-12-04 00:31:00": 14,
  <!-- more results -->
}
*/

// Convert the object back to an array representation

const finalData = Object.keys(simplifiedRecords).map(key => ({date: key, unit: simplifiedRecords[key]}))

console.log(finalData)
/*
[
  {
    "date": "2015-12-04 00:01:00",
    "unit": 15
  },
  {
    "date": "2015-12-04 00:31:00",
    "unit": 14
  },
  <!-- more results -->
]
*/

Answer №2

To effectively use the reduce function, ensure that the accumulator is an object with dates as keys. Then you can accumulate values in the units property.

You have the option to revert it back to an array using Object.values().

results = [ { unit: 5, date: '2015-12-04 00:01:00' },
          { unit: 10, date: '2015-12-04 00:01:00' },
          { unit: 5, date: '2015-12-04 00:31:00' },
          { unit: 9, date: '2015-12-04 00:31:00' },
          { unit: 5, date: '2015-12-04 01:01:00' },
          { unit: 10, date: '2015-12-04 01:01:00' },
          { unit: 10, date: '2015-12-04 01:31:00' },
          { unit: 5, date: '2015-12-04 01:31:00' },
          { unit: 10, date: '2015-12-04 02:01:00' },
          { unit: 5, date: '2015-12-04 02:01:00' },
          { unit: 5, date: '2015-12-04 02:31:00' },
          { unit: 9, date: '2015-12-04 02:31:00' },
          { unit: 5, date: '2015-12-04 03:01:00' },
          { unit: 9, date: '2015-12-04 03:01:00' },
          { unit: 5, date: '2015-12-04 03:31:00' },
          { unit: 10, date: '2015-12-04 03:31:00' },
          { unit: 10, date: '2015-12-04 04:01:00' },
          { unit: 5, date: '2015-12-04 04:01:00' }];

arr = Object.values(results.reduce((a, {
  unit,
  date
}) => (a[date] = {
  date: date,
  unit: a[date] ? a[date].unit + unit : unit
}, a), {}));
console.log(arr);

Answer №3

To organize the data by date and calculate the sum of units, follow these steps:

let indexedDates = {};
results.forEach(result => {
   let arrayByDate = indexedDates[result.date] || [];
   arrayByDate.push(result.unit);
   indexedDates[result.date] = arrayByDate;
});
let yourExpectedResult = Object.keys(indexedDates).map(date => ({
  date,
  unit: indexedDates[date].reduce((a, b) => a +b)
}));

let results = [ { unit: 5, date: '2015-12-04 00:01:00' },
      { unit: 10, date: '2015-12-04 00:01:00' },
      { unit: 5, date: '2015-12-04 00:31:00' },
      { unit: 9, date: '2015-12-04 00:31:00' },
      { unit: 5, date: '2015-12-04 01:01:00' },
      { unit: 10, date: '2015-12-04 01:01:00' },
      { unit: 10, date: '2015-12-04 01:31:00' },
      { unit: 5, date: '2015-12-04 01:31:00' },
      { unit: 10, date: '2015-12-04 02:01:00' },
      { unit: 5, date: '2015-12-04 02:01:00' },
      { unit: 5, date: '2015-12-04 02:31:00' },
      { unit: 9, date: '2015-12-04 02:31:00' },
      { unit: 5, date: '2015-12-04 03:01:00' },
      { unit: 9, date: '2015-12-04 03:01:00' },
      { unit: 5, date: '2015-12-04 03:31:00' },
      { unit: 10, date: '2015-12-04 03:31:00' },
      { unit: 10, date: '2015-12-04 04:01:00' },
      { unit: 5, date: '2015-12-04 04:01:00' }];
let indexedDates = {};
results.forEach(result => {
   let arrayByDate = indexedDates[result.date] || [];
   arrayByDate.push(result.unit);
   indexedDates[result.date] = arrayByDate;
});
let yourExpectedResult = Object.keys(indexedDates).map(date => ({
  date,
  unit: indexedDates[date].reduce((a, b) => a +b)
}));
console.log(yourExpectedResult);

Answer №4

Is this what you are looking for?

const aggregation = results.reduce((accumulator, result) => {
    const { unit, date } = result;
    accumulator[date] = accumulator[date] || { unit: 0, date };
    accumulator[date].unit += unit;
    return accumulator;
}, {});
const desiredData = Object.values(aggregation);

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

Eliminate unnecessary transparency in React Material UI Tooltip / Popper by adjusting opacity restrictions

Looking to integrate the Tooltip component from the React Material UI Library into my project. The code snippet I am using is as follows: <WhiteOnDarkGreyTooltipWithControls disableTouchListener disableFocusListener title={ <Text selectable ...

JavaScript and modifying the attributes of the nth child

I'm working on a navigation bar that changes the "background-image" of menu items using the nth-of-type CSS selector. Now, I need to figure out how to dynamically change the picture of the "background-image" when hovering over a specific menu item usi ...

Change the value of input on onClick event in React

Although this may seem simple, it is a little confusing to me. I'm having trouble understanding why the input value in the following case is not being reset. handleReset() { this.setState({ data: "" }); } <button onClick={this.handleReset}>R ...

Can I use jqPlot to create a separate division for the legend?

Is it feasible to move the legend to a distinct div using jqPlot? legend: { show: true, placement: 'outside', fontSize: '11px', location: 'n' } ...

Steps to manage the time delay between mousewheel events triggering

Currently, I am working on a website for a movie production company that showcases their various films in full-screen mode. Each video is listed and there is a function that automatically takes the user to the next video when a mousewheel event occurs. How ...

Encountering the error message: "TypeError [ERR_INVALID_ARG_TYPE]: The initial parameter should either be a string, Buffer instance, or Uint8Array."

Having trouble with the payment gateway API and subscription creation. Encountering an error that I can't seem to resolve even after debugging. Despite my best efforts, the error persists. The form and everything else seem to be in order, but the err ...

What is the best way to deactivate certain JavaScript functions on my webpage when accessed through a mobile device?

Is there a way to disable specific JavaScript functions when accessing my website from a mobile device? While I can achieve this using CSS only, certain buttons require JavaScript functionality. Below is the internal JavaScript code: var menuBtn = docume ...

Submit a HTML form to a Telegram recipient

I am looking to send HTML form data, which includes input values and select options, to a telegram user. After some research, I discovered that I need to create a Telegram bot. I successfully created one using @botFather by following these steps: /newbot ...

Calculating the total number of clicks on a button using PHP

I am attempting to track the total number of clicks on a button by individual users, rather than combining all members' clicks. Each user's clicks on the button should be logged separately. I am struggling to determine the best approach for this ...

Drawing the canvas is taking place prior to the image being fully loaded in JavaScript

Currently, I am in the process of creating a collage using images that are all sized at 174x174 pixels. The images are stored on my server, and while my program can locate them successfully, it requires me to click the "save image" button twice for them to ...

Issue: Troubleshooting data serialization process using getStaticProps in Next.js

I attempted to retrieve data from an API, but unfortunately encountered the following error: Server Error Error: Issue with serializing .results returned from getServerSideProps in "/". Reason: JSON serialization does not support undefin ...

Ways to incorporate smooth transitions to content using CSS

I recently created a website for a competition and I am looking to make the text change when a user hovers over a link. While I have managed to achieve the text change, I now want to add a transition to it. I have only used CSS to change the code. Can some ...

An Array of objects is considered NULL if it does not contain any values before being iterated through

Working with Files in TypeScript (Angular 8) has led me to Encode the files in Base64 using the code below: private async convertToBase64(evidences: Array<EvidenceToDisplay>): Promise<Array<EvidenceToDownload>> { const results: Arr ...

Can I utilize p5.Vector.fromAngle() in Vue JS?

Incorporating P5 into a Vue application can be achieved using the following code snippet: let script = p5 => { p5.setup = _ => { this.setup(p5) } p5.draw = _ => { this.draw(p5) } } this.ps = new P5(script) While functions like ba ...

Tips for incorporating animation while altering element styles within JavaScript

I am looking to incorporate a sliding animation that moves the element downward when the display property is set to block, and upward when it's set to none or an empty string, here is the current JavaScript code I have: <script> function showQ ...

Utilizing JSONP callbacks in Dart

I've been struggling with implementing basic JSONP in Dart and I can't seem to figure it out. After reading this specific blog post along with another helpful resource, it suggests using window.on.message.add(dataReceived); to receive a MessageEv ...

Using sl-vue-tree with vue-cli3.1 on internet explorer 11

Hello, I am a Japanese individual and my proficiency in English is lacking, so please bear with me. Currently, I am using vue-cli3.1 and I am looking to incorporate the sl-vue-tree module into my project for compatibility with ie11. The documentation menti ...

JavaScript in fullscreen mode for Internet Explorer

I'm trying to make sure that this code snippet... $('#gatewayDimmer').width($('html').width()); $('#gatewayDimmer').height($('html').height()); $('#gatewayDimmer').css('display','block& ...

JSDOM failing to retrieve complete list of elements from webpage

I'm currently struggling with a simple webscraper using JSDOM. Here's the code snippet I've been working on: const axios = require("axios"); const jsdom = require("jsdom"); const { JSDOM } = jsdom; let v = "15" ...

Vue: Changing the value in the select dropdown causes input fields to reset their content

After setting up a form with input values, I noticed that when using a select element with a v-model to change the dropdown value, the input fields from the previous selections are cleared. This has been a persistent issue for me and is now starting to imp ...