Obtain a collection of keys that share identical values

In my JavaScript code, I have an array of objects structured like this:

objArray = [
  {"date":"07/19/2017 12:00:00 AM","count":"1000","code":"K100"},
  {"date":"07/21/2017 12:00:00 AM","count":"899","code":"C835"},
  {"date":"07/23/2017 12:00:00 AM","count":"700","code":"C837"},
  {"date":"07/23/2017 12:00:00 AM","count":"800","code":"K100"},
  {"date":"07/23/2017 12:00:00 AM","count":"50","code":"C837"}
];

I need to extract specific data from this array by:

  • Removing duplicate date values
  • Merging the code values into an array
  • Adding up the count value for each unique date

The expected output should look like this:

newObjArray = [
  {"date":"07/19/2017 12:00:00 AM","count":"1000","code":"K100"},
  {"date":"07/21/2017 12:00:00 AM","count":"899","code":"C835"},
  {"date":"07/23/2017 12:00:00 AM","count":"1550","code":["C837","K100","C837"]}
]

I've attempted a solution but couldn't achieve the desired result. Can anyone guide me on how to process this data correctly to get the expected output?

Here's an example.

Answer №1

objArray = [
  {"date":"07/19/2017 12:00:00 AM","count":"1000","code":"K100"},
  {"date":"07/21/2017 12:00:00 AM","count":"899","code":"C835"},
  {"date":"07/23/2017 12:00:00 AM","count":"700","code":"C837"},
  {"date":"07/23/2017 12:00:00 AM","count":"800","code":"K100"},
  {"date":"07/23/2017 12:00:00 AM","count":"50","code":"C837"}
];


var groupedObjects = objArray.reduce((groupedObj, record) => {
  if (groupedObj[record.date] === undefined) {
    record.code = [record.code];
    record.count = Number(record.count);
    groupedObj[record.date] = record;
  } else {
    groupedObj[record.date].count += Number(record.count);
    groupedObj[record.date].code.push(record.code);
  }
  return groupedObj;
}, {}) 

console.log(Object.values(groupedObjects));

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

A guide on sending arrays from javascript to a Laravel controller through axios

Currently, I am utilizing Laravel 5.4 and Vue 2 to manage my data. I am facing an issue where I need to call a controller method using axios while passing two arrays. These arrays are crucial for making database requests in the controller and retrieving ne ...

Is there a way to extract data from a JSON file with dc.js?

As a beginner in programming, I am looking to learn how to import data from a JSON file using dc.js. ...

Click on each item within the v-for loop to gather relevant information, and subsequently iterate through the collected data

Within a v-for loop, I have implemented a button that, when clicked, retrieves specific data. The objective is to display this data below or in place of the clicked button. <div v-for="(item, index) in items" :key="index"> <button @click="fetch ...

Using jQuery AJAX to Redirect to a 404 Page in Case the Load Method Encounters Failure

My website utilizes AJAX to load all pages using the jQuery load method. I modified this tutorial to work with Wordpress. The issue I am facing now is that when the load method encounters an error (such as a 404 due to a broken link), the AJAX transition ...

Rendering nested JSON using React Native

After successfully loading a JSON object and storing it in this.state, I am encountering difficulty accessing nested levels beyond the initial level. Here is an example of the JSON file being used: { "timestamp": 1530703572, "trend": { "value": 0, ...

Is there a limitation with json.dumps when it comes to utf-8 encoding?

Here is a sample program that includes a Chinese character: # -*- coding: utf-8 -*- import json j = {"d":"中", "e":"a"} json_data = json.dumps(j, ensure_ascii=False) print(json_data) Below is the output. It seems like json.dumps converts the utf-8 cha ...

Understanding how to retrieve the FileType from a Document Object Model using JavaScript

Looking at this DOM structure, we have an image with the following details: <img id="this-is-the-image" src="http://192.168.1.100/Image_tmp/2016-06/d4eb8d"> The task at hand is to click a button, execute a JavaScript function, and download the ima ...

Steps for Displaying Data from API Response in Vue.js

Immediately rendering the following template, without waiting for the API call to complete. I came up with a solution using v-if to prevent elements from rendering until the data is available. However, this seems to go against the DRY principle as I have ...

"Upon setting the state in React, the Full Calendar refreshes and retrieves events

My current setup involves using the FullCalendar API to fetch events as shown below: <FullCalendar ref={calendarRef} plugins={[listPlugin, bootstrap5Plugin]} initialView='listMonth' ...

The video is not displaying on the webpage when connected locally, but it appears when the source is a URL

Recently, while practicing some basic tasks on a cloud IDE called Goorm, I encountered an issue with displaying a video on a simple webpage. The EJS file and the video were located in the same folder, but when I set the src attribute of the video tag to "m ...

What is the best way to retrieve the Axios Post response in React?

I'm facing a small issue. In my ReactJS code, I have a post function that is functioning correctly. However, I want to access the response of this function outside its scope, right where I called it. Is there a way to achieve this? async function che ...

The Node.js JSON string displays as "[object Object]" in the output

Front End // js / jquery var content = { info : 'this is info', extra : 'more info' } $.ajax({ type: 'POST', url: '/tosave', data: content }); Node // app.js app.post('/tosave', funct ...

Filtering data in Laravel can be efficiently achieved by utilizing Laravel's ORM hasmany feature in conjunction with Vue

Hey there, I'm currently working with Laravel ORM and Vue 2. I've encountered some issues with analyzing Json data. Here's my Laravel ORM code: $banner = Banner::with('banner_img')->get(); return response()->json($banner); ...

Using jQuery's toggle function with a double click event to change the display to none

A div I created has the ability to expand to full screen upon double click, and I now wish to implement a toggle function so it can return to its original size when double clicked again. Initially, the code successfully increased the size of the div. Howe ...

Is it possible that React.createElement does not accept objects as valid react children?

I am working on a simple text component: import * as React from 'react' interface IProps { level: 't1' | 't2' | 't3', size: 's' | 'm' | 'l' | 'xl' | 'xxl', sub ...

I am having trouble getting the hoverOffset feature to work with doughnut charts in vue-charts.js

It appears that no matter what I try, the hoverOffset property is not working on my doughnut charts. Here's the component code: <script> import { Doughnut } from 'vue-chartjs' export default { extends: Doughnut, props: { ch ...

The Google Apps Script will activate only on weekdays between the hours of 10 AM and 5 PM, running every hour

function Purchase() { var ss=SpreadsheetApp.getActive(); var sheet=ss.getSheetByName("Buy"); var Cvalues=sheet.getRange(2,3,sheet.getLastRow()-1,1).getValues(); var Avalues=sheet.getRange(2,1,sheet.getLastRow()-1,1).getValues(); var r ...

What is the best way to handle the resolution of multiple promises as they complete?

Suppose I have three different promises each taking a varying amount of time to resolve - 1000ms, 2000ms, and 3000ms respectively. How can I simultaneously start all the promises and handle them as they get resolved? For instance: let quickPromise = new ...

Refresh cloned element after making changes to the original element

Just starting to explore Jquery and looking for some guidance to get me started :) Question: I'm facing an issue with a cart total price that is displayed in a different part of the page using clone(). I want this cloned price to automatically update ...

Best Practices for Implementing Redux Prop Types in Typescript React Components to Eliminate TypeScript Warnings

Suppose you have a React component: interface Chat { someId: string; } export const Chat = (props: Chat) => {} and someId is defined in your mapStateToProps: function mapStateToProps(state: State) { return { someId: state.someId || '' ...