Combining multiple objects in an array to create a single object with the aggregated sum value can be achieved using JavaScript

I am working with an array that contains numbers of array objects, and I need to merge these arrays into a single array with unique values for content and the sum of values for total as shown in the desired result below. Any assistance would be greatly appreciated.

Result Set

[
  [
    {
      content: 'Aqurie',
      total: 5
    },
    {
      content: 'Mail function',
      total: 4
    }
  ],
  [
    {
      content: 'Aqurie',
      total: 4
    },
    {
      content: 'Mail function',
      total: 10
    }
  ]
]

Desired Result

[
  {
    content: 'Aqurie',
    total: 9
  },
  {
    content: 'Mail function',
    total: 14
  }
]

My current approach to achieving this is:

var transformed = arr.reduce(function(a, b){ return a.concat(b); });
console.log(transformed); 

Answer №1

If the order of elements in the nested arrays remains the same, you can use the following method:

var arr = [
  [{
    content: 'Aqurie',
    total: 5
  }, {
    content: 'Mail function',
    total: 4
  }],
  [{
    content: 'Aqurie',
    total: 4
  }, {
    content: 'Mail function',
    total: 10
  }]
];

// Use reduce function to merge the arrays
var res = arr.reduce(function(a, b) {
  // Iterate over the arrays to update the total values
  var ret = a.map(function(v, i) {
    v.total += b[i].total;
    // Return the updated object
    return v;
  });
  // Return the merged array
  return ret;
});

document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');


UPDATE 1 : If the order is random, add an additional for loop inside map() to compare the content property.

var arr = [
  [{
    content: 'Aqurie',
    total: 5
  }, {
    content: 'Mail function',
    total: 4
  }],
  [{
    content: 'Mail function',
    total: 10
  }, {
    content: 'Aqurie',
    total: 4
  }]
];

// Use reduce function to merge the arrays
var res = arr.reduce(function(a, b) {
  // Iterate over the inner arrays and update total value based on content
  var ret = a.map(function(v) {
    // Use a for loop to find the matching index in the array
    for (i1 = 0; i1 < b.length; i1++) {
      // Check content for matching
      if (v.content == b[i1].content) {
        // Update the total value if matched
        v.total += b[i1].total;
        // Break the loop on match
        break;
      }
    }
    // Return the updated array
    return v;
  });
  // Return the merged array
  return ret;
});

document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');


UPDATE 2 : The previous method may not work for certain cases where it only updates the total of the first array values. For example, if the second array contains different content, it will be skipped.

var arr = [
  [{
    content: 'Aqurie',
    total: 5
  }],
  [{
    content: 'Mail function',
    total: 10
  }, {
    content: 'Aqurie',
    total: 4
  }],
  [{
    content: 'other',
    total: 4
  }]

];

// Use reduce function to merge the arrays
var res = arr.reduce(function(a, b) {
  // Iterate over inner arrays and update total value based on content
  b.forEach(function(v) {
    // Use a for loop to find the matching array index
    var found = false;
    for (i1 = 0; i1 < a.length; i1++) {
      // Check content for matching
      if (v.content == a[i1].content) {
        found = true;
        // Update the total value if matched
        a[i1].total += v.total;
        // Break the loop on match
        break;
      }
    }
    // Push the element if a new element is found
    if (!found)
      a.push(v);
  });
  return a;
});

document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');


Answer №2

Give it a shot,

const flattenAndSum = (arr) => {
  const newArr = [];
  let existing;
  arr.forEach((itm) => {
    itm.forEach((inner) => {
      existing = findIt(inner, newArr);
      if(existing){
        existing.total += inner.total;
      } else {
         newArr.push(inner);
      }
    });
  });

  return newArr;
}

const findIt = (obj, newArr) => {
 for(let i = 0; i < newArr.length; i++) {
   if(newArr[i].content === obj.content){
     return newArr[i];
   }
 }
}

console.log(flattenAndSum(arr));

Check out the DEMO

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

What is the correct method to choose an element in jQuery based on the function's id parameter

I'm having trouble deleting an item in my to-do list app. deleteToDoItem: function(id) { $(id).remove(); console.log(id); }, Here is the function that calls deleteToDoItem: function deleteItem(event) { var itemID, splitID, t ...

The absence of CORS headers detected in XMLHttpRequest

I am currently trying to execute an ajax call to a remote server, only for developmental purposes. I have configured CORS on my server, which is why when I request the resource through the browser, it shows that the CORS headers are present. https://i.sta ...

UI thread was blocked due to withProgress being invoked from an external library function

Currently enhancing an extension that is almost finished, but facing a challenge in adding visual cues for lengthy operations. Initially suspected a missing async/await in the code, but struggling to identify the cause. The progress indicator isn't di ...

Encountering an issue when trying to start npm in the command line interface

Here is the content of my package.json file: "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, This project was created using create-react-app. Ho ...

methods for sharing real-time data between parent and child components in Angular versions 2 and above

When working with Angular, we are familiar with parent to child communication using the @Input decorator. However, the challenge arises when we need to pass dynamic data from the parent to the child component. Imagine having a 'name' property def ...

Searching for identical consecutive numbers in a grid

Hi there, I'm currently working on developing a function that can detect if a N*N matrix contains at least two adjacent numbers (ranging from 0 to h-1) in the up-down-left-right directions. The function should return 1 if such numbers are found, and 0 ...

Combine functions from two objects that share the same properties into an array for each property

I need help combining the methods from two objects into one, resulting in an array of methods for each property in the parent object: obj1 = {"prop1":"method1","prop2":"method2"} obj2 = {"prop1":"method3","prop2":"method4"} Expected result: obj1 = {"pro ...

Is TypeScript's nullish coalescing operator (??) supported by more browsers compared to JavaScript's equivalent?

When it comes to the nullish coalescing operator (??) in JavaScript, browser support is limited to newer browsers such as Chrome 80, Edge 80, and Firefox 72. Since TypeScript gets converted to JavaScript, do nullish coalescing operators also undergo some ...

MongoDB has encountered an issue where it is unable to create the property '_id' on a string

Currently, I am utilizing Node.js and Express on Heroku with the MongoDB addon. The database connection is functioning correctly as data can be successfully stored, but there seems to be an issue with pushing certain types of data. Below is the database c ...

Using Regular Expressions in an ExpressJS Router

When working with ExpressJS, is there a way to combine the following routes into one using RegEx? app.get(/^\/blog(?:\/p(\/\d+)?)?$/, blog.list); ...

Ways to Randomly Flip Divs

I have developed an application where all divs flip vertically on hover. I am looking for a way to make the flipping random without requiring a hover. Any ideas on how to achieve this? .vertical.flip-container { position: relative; float: left; ma ...

Using Jquery to extract URL parameters

Can anyone suggest a jQuery function I can use to fetch URL parameters? I've been utilizing the following function, which works well; however, it encounters issues when the URL doesn't have any parameters. I would like it to return an empty stri ...

How can I transfer a collection of JSON objects from JavaScript to C#?

Feeling a bit confused here. I have some Javascript code that will generate JSON data like the following: {type:"book" , author: "Lian", Publisher: "ABC"} {type:"Newspaper", author: "Noke"} This is just one example, I actually have more data than thi ...

What is the best way to draw a rectangle outline in Vue.js without the need for any additional packages?

I have been attempting to craft a rectangle outline using vueJS, but so far I have not had much success. I am hoping to achieve this using only CSS, but despite my efforts, I have not been able to find a solution. My goal is to create something similar to ...

Failed to retrieve the requested item using fetch, encountering a NetworkError

My API is being accessed to retrieve data using this code snippet. It sends the email and password to the API: onSubmitSignIn = () => { fetch('http://localhost:3001/signin', { method: 'post', headers: {'Content-Type&ap ...

The total height of the document's body in jQuery is not equal to the sum of the viewport height and the window's scroll top position at the bottom of the document

Why does the document height appear smaller than the window scroll top value plus the viewport height when I reach the end of the document? Shouldn't they be equal? I've been struggling with this issue for hours and can't seem to figure it o ...

Breaking or wrapping lines in Visual Studio Code

While working in Visual Studio Code, I often encounter the issue of long lines extending beyond the screen edge instead of breaking and wrapping to the next line. This lack of text wrapping can be quite bothersome. I utilize a split-screen setup on my co ...

Displaying child properties in a functional ReactJS component

React version 0.14 introduces the concept of pure functional components, ensuring that the same input always results in the same output. Props are passed as function arguments. // Using ES6 arrow functions with implicit return: const PureComponent = ({url ...

Tips for managing boolean values in a JSON data structure

My JSON object is causing issues because it has True instead of true and False instead of false. How can I fix this problem? The code snippet below shows that obj2 is not working properly due to boolean values being capitalized. <!DOCTYPE html> < ...

Submit the chosen options as an array

I am working with a select list in HTML that looks like this: <input type="checkbox" name="drive_style" value=1 checked />123<br /> <input type="checkbox" name="drive_style" value=2 />123<br /> <input type="checkbox" name="drive ...