How to merge duplicates in an array of objects and sum a specific property? [dup
ID: 3876429 • Letter: H
Question
How to merge duplicates in an array of objects and sum a specific property? [duplicate]. I am creating a JS chart, which I have done succesfully but I a lot having duplicates . Below is a sample JSON where I am retrieving data from to display on my Bar chart. I want to sum the duplcate values.
<counts>
<serial>3123111</serial><scans>3</scans><prints>1</prints><copies>0</copies>
</counts>
<counts>
<serial>3123111</serial><scans>0</scans><prints>2</prints><copies>0</copies>
</counts>
<counts>
<serial>AHTSD111</serial><scans>0</scans><prints>1</prints><copies>2</copies>
</counts>
<counts>
<serial>AHTSD111</serial><scans>0</scans><prints>1</prints><copies>2</copies>
</counts>
expected result below
====================================================================================
<counts>
<serial>3123111</serial><scans>3</scans><prints>3</prints><copies>0</copies>
</counts>
<counts>
<serial>AHTSD111</serial><scans>0</scans><prints>2</prints><copies>4</copies>
</counts>
===================================================================================
$.ajax({
url: "http://localhost/api/Num",
dataType: 'json',
method: "GET",
success: function (data) {
parser = new DOMParser();
var xmlDoc = parser.parseFromString(data, "text/html");
data = xmlDoc.getElementsByTagName("JobCounts");
console.log(data);
var serial = [];
var prints = [];
var scans = [];
var copies = [];
for (i = 0; i < data.length; i++) {
serial.push("#" + data[i].getElementsByTagName("Serial")[0].textContent);
prints.push(data[i].getElementsByTagName("Prints")[0].textContent);
copies.push(data[i].getElementsByTagName("Copies")[0].textContent);
scans.push(data[i].getElementsByTagName("Scans")[0].textContent);
}
Explanation / Answer
Instead of using arrays for each attribute, you can implement map in javascript as below.
var map = {};
for (i = 0; i < data.length; i++) {
var serial = data[i].getElementsByTagName("Serial")[0].textContent;
var prints = data[i].getElementsByTagName("Prints")[0].textContent;
var copies = data[i].getElementsByTagName("Copies")[0].textContent;
var scans = data[i].getElementsByTagName("Scans")[0].textContent;
if(serial in map) { // if key already exists in map then sum the previous and current values
prints += map[serial].Prints; // retrieves the 'Prints' property value form already existed serial
copies += map[serial].Copies;
scans += map[serial].Scans;
}
map[serial] = {"Prints":prints, "Copies":copies, "Scans":scans};
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.