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

Leveraging the replace feature within Selenium IDE

After extracting information from a webpage, I found a string that read "price: $30.00" which I saved as "x." What I really needed was just the numbers - "30.00". I attempted to use x.replace(), but unfortunately it didn't work out. If anyone could as ...

Incorporate variable key-value pairs into a JavaScript array or object

Is it possible to add a key value pair to an existing JavaScript associative array using a variable as the key? I need this for JSON encoding and prefer a simple solution over using plugins or frameworks. ary.push({name: val}); In the above code snippet, ...

Leveraging REST API for Ensuring Users in SharePoint 2013

I am currently working on automatically ensuring users via a REST API. Here is my REST call: $.ajax({ url: "blablabla/_api/web/ensureuser", type: "POST", data: "{ 'logonName': 'i%3A0%23.w%7Cdomain%09logonName' }", headers: { "X-Req ...

Activate night mode in ElementPlus using CDN

Is there a way to set the theme to dark in ElementUI + Vue when using CDNs instead of npm? <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width,initial-scale=1.0" /> ...

The updating of Angular 2 CLI variables does not occur

As a complete newcomer to Angular 2, I recently attempted to start my first project using the Angular CLI. Unfortunately, I encountered some issues. It seems that the variables in my views are not updating as expected. I followed the typical steps: ng n ...

Frisby.js is looking for a valid JavaScript object, but instead received an undefined value

Struggling to launch a new test using the API testing framework Frisby.js. In my previous tests that didn't involve reading reference files from disk, everything ran smoothly and quickly. The samples provided with Frisby also executed accurately. Thi ...

Harness the power of JSON data within your iOS applications. Unleash its capabilities

After developing a web service that I believed was returning JSON data, I examined the output: {"invoice":{"id":44,"number":42,"amount":1139.99,"checkoutStarted":true,"checkoutCompleted":true}} Based on my understanding, this appeared to be valid JSON. ...

unable to decipher a JSON file obtained from Instagram

I have been working on a project that involves parsing a JSON file obtained from the Instagram API. However, I am facing an issue where I can parse the data but I cannot read it properly in my code: <!DOCTYPE html> <html> <head> <meta ...

What is the method to store anchor text in a Session variable?

I'm currently working on a project where I've linked multiple pdf files in the master page. When clicking the anchor, the page redirects to the specified location and displays the pdf in an iframe. Now, I want the text within the anchor tag to be ...

Enhance user interaction in Angular 13 by animating a selected element using just one animation block

I am currently working on a one-page website project to enhance my Angular skills, and I'm facing a challenge with animating multiple DOM elements using a single animation. Defining the animation for each element individually seems like a cumbersome a ...

Increase numbers with uniform speed using jQuery for each number

I am working on implementing a jQuery script that will visually increase any number from zero to its value using setInterval(). Here is the current solution I have come up with: $('.grow').each(function() { var $el = $(this); va ...

Unpacking JSON data

There is a json file containing 908 rows of data, with various hardware Class types. Each grouping includes the following structure, with Properties varying based on the component type. "HardwareID": "ACPI\\AuthenticAMD_-_AMD64_Family_16_Model_ ...

Filtering elements using two dropdown lists

In my list, each li element has data-name and data-body attributes. I want to display only the li elements that match the selected values. The first select option is for selecting the car name, while the second select option is for selecting the car body. ...

displaying a pair of distinct elements using React techniques

I need help adding a react sticky header to my stepper component. When I try to render both components together, I encounter an error. To troubleshoot, I decided to render them separately. Surprisingly, when rendering separately, I do not get the "store is ...

Using ng-pattern to validate that a text field does not conclude with a particular term

In this code snippet, I am attempting to prevent a textfield from ending with any of the specified letters in the $scope.pointPattern variable. $scope.pointPattern = /^(?!.*ess|ence|sports|riding?$)/; $scope.error = "not valid"; Upon executio ...

Execute an executable file with elevated permissions using Node.js

I'm looking to run an .exe file as an administrator using Node. I attempted the following code, but it's not working: exec('runas /user:Administrator "app.exe"', function(err, data) { console.log(err) ...

Is it possible to iterate over an array and invoke a function at the same time?

const students = ['John', 'Mark']; const weight = [92, 85] const height = [1.88, 1.76] function yourBodyMass(name, funct, mass, height) { console.log(`${name}, your body mass index is ${funct(mass, height)}.`) } function calculateBM ...

Unable to get Express router post function to properly function

Issue: var express = require('express'); var router = express.Router(); Route.js: Setting up Post route router.route('/signup') .post(function (req, res) { console.log('post signup called', req.body); re ...

Save the retrieved JSON data as state and utilize it

I'm just starting out with React and I'm eager to grasp the fundamental concepts. Currently, I am experimenting with fetching data from an API that I manually input some data into for educational purposes. This is achieved using a fetch request ...

Setting the row ID value after performing form editing in free jqGrid

In the table, there is a primary key with 3 columns (Grupp, Kuu, Toode), and the server returns an Id created from those columns. When the primary key column is changed in form editing, the server sends back a new row id. However, Free jqgrid does not se ...