One way to combine two elements from an array in JavaScript is by comparing their dates (or any other similar element)

Currently, the array is structured as follows:

array = [
 {
  date: '2020/06/12',
  hours: 8.4
 },
 {
  date: '2020/06/15',
  hours: 4.5
 },
 {
  date: '2020/06/12',
  hours: 3.8
 },
 {
  date: '2020/06/16',
  hours: 5.5
 },
]

The objective is to combine and filter out duplicated dates in order to sum their corresponding hours. For example, with the given array above where the day 12 occurs twice, the result should be as follows:

array = [
 {
  date: '2020/06/12',
  hours: 12.2
 },
 {
  date: '2020/06/15',
  hours: 4.5
 },
 {
  date: '2020/06/16',
  hours: 5.5
 },
]

Answer №1

To consolidate data, consider utilizing a reducer function:

const mergedData = dataArray.reduce((accumulator, current) => {
   const previous = accumulator.find(elem => elem.date === current.date);
    if(previous) {
        previous.hours += current.hours;
    } 
    else {
        accumulator.push(current);
    }
    return accumulator;
}
, []);

Answer №2

function groupHoursByDate(arrayOfObjects, property) {
  let i = 0;
  let val;
  let index;
  const values = [];
  const result = [];
  for (; i < arrayOfObjects.length; i++) {
    val = arrayOfObjects[i][property];
    index = values.indexOf(val);
    if (index > -1) result[index].push(arrayOfObjects[i]);
    else {
      values.push(val);
      result.push([arrayOfObjects[i]]);
    }
  }

  const newArray = [];

  for (const x of result) {
    let totalHours = 0;
    let currentDate;
    for (const obj of x) {
      currentDate = obj.date;
      totalHours += obj.hours;
    }

    newArray.push({
      date: currentDate,
      hours: totalHours,
    });
  }

  return newArray;
};

// Call the groupHoursByDate function
const groupedHours = groupHoursByDate([{
    date: '2020/06/12',
    hours: 8.4
  },
  {
    date: '2020/06/15',
    hours: 4.5
  },
  {
    date: '2020/06/12',
    hours: 3.8
  },
  {
    date: '2020/06/16',
    hours: 5.5
  },
], "date");

console.log(groupedHours);

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

The Vue.js Vuetify.js error message is saying "A mystery custom element: <v-list-item>, <v-list-item-title> - Have you properly registered the component?"

I followed the instructions from Vuetify Data Iterator Filter section I am able to use various Vuetify components like v-btn, v-card, v-data-table, v-data-iterator, and more. However, I encountered errors only with <v-list-item> and <v-list-item ...

The Cytoscape layout you are looking for, "cola", does not exist

I am currently utilizing Cytoscape within an Angular 2 project that incorporates Typescript and I am attempting to implement the Cola layout. So, I included the dependency in my project via npm. As I am working with Angular 2 using Typescript, I first adde ...

What steps can be taken to revert this Node.js module to a particular version and ensure it does not automatically update in

While using the Nodemailer module in node.js, I encountered a specific error that read as follows; [Error: Unsupported configuration, downgrade Nodemailer to v0.7.1 or see the migration guide https://github.com/andris9/Nodemailer#migration-guide] A ...

Setting variables in AngularJS services without encountering JavaScript undefined errors

After developing an AngularJS module, I attempted to link a service and use it to share variables across the application. While most things are functioning properly, I encountered an issue when trying to set submenu[1] to an object. The error message sta ...

An error occurred due to a state update being attempted on an unmounted component. The solution is to properly cancel all subscriptions and asynchronous tasks in a

Currently, I am attempting to utilize ListEmptyComponent within a FlatList. If there is no data present, I intend to display ListEmptyComponent={} However, in the Loadingsecond component, I am using useEffect to render when loading is true; if there is s ...

Utilizing Javascript to implement a tooltip feature for dynamically inserted text

I recently incorporated a brief jQuery tooltip plugin into my site. It consists of approximately ten lines of code and works smoothly, as demonstrated in this demo. However, I encountered an issue when attempting to add new text that should also trigger t ...

The functionality of Selection.modify is unfortunately limited when it comes to input and textarea elements in Firefox

Check out this demonstration (jsfiddle link): const input = document.querySelector('#input'); const textarea = document.querySelector('#textarea'); const div = document.querySelector('div'); const x = (e) => { if (e.ke ...

Typescript check for type with Jest

Assume there is an interface defined as follows: export interface CMSData { id: number; url: string; htmlTag: string; importJSComponent: string; componentData: ComponentAttribute[]; } There is a method that returns an array of this obj ...

Tips for inputting text into a Slickgrid cell

Currently, I am working on a project involving an AngularJS application with a Slickgrid component. However, I have encountered a challenge when attempting to write a test for it. Despite successfully using Selenium to click on the cells within the grid, t ...

What are the limitations of processing Ajax requests with jQuery?

Let me share the scenario with you, I currently possess these 2 files: I have a page containing an empty div #responsecontainer which includes the following script at the end: <script type="text/javascript"> jQuery(document).ready(function ($) { ...

The infinite loading feature in Vue JS does not function properly when used within a v-else directive

Hey there, I'm trying to implement a Vue infinite loading feature in my template under certain conditions but for some reason it's not working. <generic-button v-if="!viewMore" inline no-arrow @click="viewMore = true" ...

A script error occurs exclusively on dynamic routing in a static web page generated by NUXT

Currently working on a Nuxt.js website and encountering an issue. Initially, nuxt.config.js was set up as below to enable a headless CMS. export default { target: "static", ssr: true, generate: { async routes() { const pages = awa ...

Different ways to repeatedly call a function returning a promise in synchronous fashion

For instance, I have a function that uses Promise.resolve() to return a cached entity id if available, but if not, it makes an ajax call to reserve a new entity id and then returns the newly reserved id. function getReservedEntityId(collectionName) { ...

Implementing an event listener on a mesh operation

I tried implementing a function in Three.js to create a sphere and wanted to add an event listener to log the value of textureToShow when it's clicked. However, when I tested it, nothing showed up in the console. Below is the code I used: function cre ...

Embed a React component within another component

Recently, I've started learning React and I'm utilizing material-ui for my project. My goal is to create a customized autocomplete feature in React where selected data from the dropdown will appear as chips inside the text input field. I am curre ...

There seems to be confusion surrounding the $.isArray() function in jQuery

I'm currently trying to determine whether the p array is valid or not. I'm not sure if I'm on the right track or if I'm making a mistake. I am currently studying the jQuery.isArray method. I suspect that there may be an error in my code ...

What's the best way to separate and save data in a variable in JavaScript?

I need to split this code and store it in three different variables, like a=GD11, b=GDP7 and c=GD11, but I am having trouble because breaking at "s" results in "GDP7xGD11". Can someone please help me figure out how to break it into three separate variable ...

Scraping a JavaScript page using Python without requiring a browser installation

Currently, I am facing a challenge in scraping an HTML element from a webpage. The content within this element is dynamically generated by Javascript, making it impossible to retrieve using a simple requests.GET: response = requests.get(url). While explor ...

Fix the Book class in order to achieve the desired result when calling the getBooksByAuthor method

Does anyone have a solution for the issue I'm facing with the getBooksByAuthor method? It's not returning any output, although the other methods are functioning properly. I'm looking for a solution that involves changing only the Book class ...

Encountering the error "Cannot read property 'header' of undefined" while conducting tests on Nodejs using supertest

In my server.js file, I have set up my express app. I tried to run a demo test in my test file using express, but unfortunately, the test did not run successfully. const request = require('supertest'); const express = require('express' ...