What is the best way to combine an array of objects by matching property values?

I'm facing an issue that involves working with an array of objects and adding their values where the dates are equal.

Here is the initial array:

0: {date: "07-04-2020", value: 10}
1: {date: "10-04-2020", value: 20}
2: {date: "07-04-2020", value: 30}
3: {date: "14-04-2020", value: 60}

The expected result should be:

0: {date: "07-04-2020", value: 40}
1: {date: "10-04-2020", value: 20}
3: {date: "14-04-2020", value: 60}

Despite trying various higher order functions like filter, map, and reduce, I am still unable to solve this problem.

Answer №1

An alternative approach is to utilize the Array.reduce method:

[...].reduce((accumulator, currentValue) => {
  // Search for an item with the same date
  const existingItem = accumulator.find(item => item.date === currentValue.date);
  // If not found, add the new item to the array
  if (!existingItem) {
    return [...accumulator, currentValue];
  }
  // If found, update the value property and return the array
  existingItem.value += currentValue.value;
  return accumulator;
}, []);

Answer №2

Do you think this solution will meet your needs?

let arrayOfObjects = [{
    date: "07-04-2020",
    value: 10
  },
  {
    date: "10-04-2020",
    value: 20
  },
  {
    date: "07-04-2020",
    value: 30
  },
  {
    date: "14-04-2020",
    value: 60
  },
]

function sumValuesWithSameDate(arr) {
  let resultArr = [];
  let tempObj = {};

  arr.forEach((row) => {
    tempObj[row.date] = tempObj[row.date] ? tempObj[row.date] + row.value : row.value;
  });

  Object.entries(tempObj).forEach((dateValue) => {
    resultArr.push({
      date: dateValue[0],
      value: dateValue[1]
    });
  });

  return resultArr;
}
console.log(sumValuesWithSameDate(arrayOfObjects));

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: The request from http://localhost:8383 to AngularJS MySQL REST API is being blocked due to Access-Control-Allow-Origin policy

Greetings from a newcomer on 'stackoverflow.com'! I'm encountering an issue with my AngularJS Application and I'm hopeful that the community here can provide some guidance. To begin with, I've set up a new maven webapp project ut ...

The ComponentDidUpdate function treats the previous state (prevState) and the current state (this

Initially, I had a state update function that looked like this: doChangeValue(data) { const dataNew = this.state.data dataNew[data.id] = data.value this.setState({ ...dataNew, [dataNew[data.id]]: data.value}) } However, I realized that thi ...

Creating a list of elements in an array without assigning it a name

I am encountering an issue where I can successfully perform a C cast of an initializer list for an array of char strings, but am unable to achieve the same result with a C++ cast (static_cast): int main() { char x[] = "test 123"; // This works fine ...

Tips for effectively reusing the modal component in Vue.js without encountering re-render issues

I'm encountering an issue where the same component content is being rendered despite having different components (Rendering problem). I have a reusable modal component called modal.vue, so every time I create a new component, I call the modal compone ...

Retrieving multiple data using jQuery's ajax functionality

I am encountering an issue with this code where I can only retrieve either the recaptcha_response_field or the recaptcha_challenge_field, but not both at the same time. This results in me being able to send only one data. challengeField = $("#recaptcha_ ...

Is It Best to Override Behavior in a Directive?

Having two directives that display lists of documents, one for user-favorited documents and the other for user-pinned documents. The criteria for displaying these documents depend on the values of "pinned" and "favorite" within each document object: docum ...

Having trouble with the jQuery function not working as expected? Can't seem to identify any errors in the code?

I'm attempting to capture the essence of moving clouds from this beautiful theme: (I purchased it on themeforest, but it's originally designed for tumblr) Now, I want to incorporate it into my wordpress website here: The code used to be under ...

Interpret an item based on its specific axis in that location

Being new to three.js, I am facing a challenge with translating an object imported from Maya. The issue arises after rotating the object; when I attempt to move it afterward, it moves along the scene's axis instead of in the direction of the rotation. ...

Express.js using GET request to retrieve all data entries from the database

I am facing a challenge in retrieving specific user data using the GET method on Express.js through a Form. Instead of returning only one user's information, it is currently returning all values when the form is used. Here is the code from index.html ...

Populate a vacant buffer in C++ with a specific value

Excuse me if my terminology isn't entirely correct, I'm still getting the hang of C++ programming. I've developed a class that includes a constructor responsible for initializing an empty buffer using malloc LPD6803PWM::LPD6803PWM(uint16_t ...

The first Ajax call was successful, but the second Ajax call was unexpectedly sent twice

After making an AJAX call to post the value of a textarea to the database, I have noticed a strange issue. The first post always goes through correctly. However, when attempting to post another entry, the AJAX call seems to be executed twice. Subsequently, ...

Aligning the content in the center of a div with inline display

Hi there, I have a quick question for the experts out there. I'm new to all of this so please bear with me :) I'm attempting to center an inline social sharing div on my website, but it's proving to be quite challenging. The div is nested w ...

"Clicking on a link inside a div element using the onclick

Hey there! I'm having an issue with a div that contains a link with an onclick event (see the code snippet). Inside this div, there is another link that goes to a different page than the div itself. The code works perfectly fine in IE, Chrome, and Fir ...

Retrieve both the keys and values from a deeply nested JSON object

My goal is to retrieve JSON data with a specific structure as shown below: {"Points": {"90": {"0": {"name": "John Phillip", "slug": "john"}, {"1&q ...

unable to activate toggleclass('d-block') for multiple radio inputs

We have multiple radio input options. function showReferral() { document.querySelector('#referral_code').classList.remove('d-none'); } <div class="form-group row d-none" id="referral_code"> <label for="referral_code"&g ...

React - Clearing State data retrieved from axios request

I am currently facing an issue with resetting the state of an object in my users array upon clicking the delete button. Even after successfully removing the object from the database, the state does not update as intended. I have managed to verify the prese ...

Using AngularJS, rearrange the text in a text area

Here is a textarea with some content displayed: <textarea id="textfield"><img src="smile.png alt=":)"/>Hi</textarea> I have implemented this JavaScript code snippet to extract the img alt value and the text Hi from the textarea in order ...

What is the reason behind Rxjs switchMap only emitting the final value from an of() observable source?

Here are two code snippets, one using map and the other using switchMap. The functionality of map is clear: of('foo', 'bar') .pipe(map((val) => sanitizer(val))) .subscribe((val) => console.log('value:', val)); func ...

What is the best way to connect to a JSON key that is consistently returned with a varying or unpredictable name?

I am currently working on an Angular 4.x application where my goal is to showcase a random Wikipedia article. Each time I check the JSON data in Chrome Dev Tools under query/pages, I notice that the pageID always has a different number. The structure of th ...

Rhythmic foliage icon created with dynamic CSS3 animations

I am looking to develop a unique animated map marker icon for my Leaflet map without relying on third-party plugins to enhance my learning experience. My current approach involves using CSS to create a 'pulsating' animation effect: .gps_ring { ...