Combining arrays depending on the designated tag in JavaScript

I am struggling to solve this problem.

For each customer, I have an array object representing each month of the year:

[
  {
    color: "#009192",
    data: [0, 0, 57.62, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    label: "Client 1"
  },
  {
    color: "#009192",
    data: [0, 0, 234.65, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    label: "Client 2"
  },
  {
    color: "#009192"
    data: [0, 0, 490.43, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    label: "Client 3"
  },
  {
    color: "#009192"
    data: [0, 0, 0, 94.00, 0, 0, 0, 0, 0, 0, 0, 0]
    label: "Client 1"
  }
]

How can I combine the two objects with the same label (Client 1) and create a new array like this?

[
  {
    color: "#009192",
    data: [0, 0, 57.62, 94.00, 0, 0, 0, 0, 0, 0, 0, 0],
    label: "Client 1"
  },
  {
    color: "#009192",
    data: [0, 0, 234.65, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    label: "Client 2"
  },
  {
    color: "#009192"
    data: [0, 0, 490.43, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    label: "Client 3"
  },
]

Appreciate your help!

Answer №1

If you want to consolidate data arrays with the same label, you can utilize Array#reduce by creating an object to store values for each label and summing up the arrays that share the same label.

let arr=[{color:"#009192",data:[0,0,57.62,0,0,0,0,0,0,0,0,0],label:"Client 1"},{color:"#009192",data:[0,0,234.65,0,0,0,0,0,0,0,0,0],label:"Client 2"},{color:"#009192",data:[0,0,490.43,0,0,0,0,0,0,0,0,0],label:"Client 3"},{color:"#009192",data:[0,0,0,94,0,0,0,0,0,0,0,0],label:"Client 1"}];
let res = Object.values(arr.reduce((acc, {color,data,label}) => {
  if (acc[label]) acc[label].data.forEach((x, i, a) => a[i] += data[i]);
  else acc[label] = {color, data, label};
  return acc;
}, {}));
console.log(JSON.stringify(res));

Answer №2

I hope this solution proves to be useful for you.

one = [
  {
    color: "#009192",
    data: [0, 0, 57.62, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    label: "Client A"
  },
  {
    color: "#009192",
    data: [0, 0, 234.65, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    label: "Client B"
  },
  {
    color: "#009192",
    data: [0, 0, 490.43, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    label: "Client C"
  },
  {
    color: "#009192",
    data: [0, 0, 0, 94.00, 0, 0, 0, 0, 0, 0, 0, 0],
    label: "Client A"
  }
];

console.log(one)

let two = one.reduce((acc, cur) => {
    //console.log(acc);

    let index = (!acc.length ? null : acc.findIndex((item) => item.label === cur.label));

    if (index !== null && index >= 0) {
        acc[index].data = acc[index].data.map((value, i) => acc[index].data[i] += cur.data[i]);
    } else {
        acc.push(cur)
    }
    
    return acc;
}, []);

console.log(two);

Best Regards

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

Navigating a plethora of unpredictable identifiers using AngularJS

My goal is to display content from a json file that varies in type and consists of pages divided into chapters. Users can navigate through the content using an aside menu or next and previous buttons. Currently, I am able to display the content by inserti ...

Do PLPGSQL arrays begin indexing at 1?

In my experience, I've noticed that in PLPGSQL the first index of an array starts at 1 by default, which is different from the usual convention of starting at 0 in most programming languages. It piqued my curiosity as to why this is the case and if th ...

What is the best way to include additional information in yii activeform's ajax parameters?

My goal is to trigger an ajax request when a radio button is clicked. Below is the code I am currently working with: <?php echo $form->dropDownListRow($model, 'page', $pages, array('class' => 'span5', 'prompt&ap ...

Discovering all the links present on a webpage using node.js

Currently, I am diving into node.js (webdriver) and encountering some challenges. Despite my efforts to search online for examples of the tasks I need help with, I have come up empty-handed. One example that has me stumped is how to log all links from a pa ...

Oops! Looks like there's an unexpected error with the module 'AppRoutingModule' that was declared in the 'AppModule'. Make sure to add a @Pipe/@Directive/@Component annotation

I am trying to create a ticket, but I encountered an error. I am currently stuck in this situation and receiving the following error message: Uncaught Error: Unexpected module 'AppRoutingModule' declared by the module 'AppModule'. Plea ...

I'm surprised by the fact that array.findIndex is not functioning properly. According to Mozilla, it should be working fine

It was necessary to change state.findIndex to state.ids.findIndex in order to resolve the issue I was facing. However, an unexpected behavior occurs when calling the function onClick, as it automatically updates ALL of the active values to true, instead o ...

Eliminating identical characters shared between two strings

I am looking to eliminate any characters that match between two strings. For example: string str1 = "Abbbccd"; string str2 = "Ebbd"; From these strings, I want the output to be: "Abcc", where only the matching characters present in both str1 and str2 ar ...

Converting the data in this table into an array of objects using JavaScript

Trying to transform the source table data into a grouped format. https://i.sstatic.net/I7PsO.png Desired grouped data structure: https://i.sstatic.net/xP2Ow.png Transformed the source table into an array of objects representing rows and columns. [ { r ...

Exploring Meteor's FS Collection: A guide to efficiently iterate and access CSV files

In my Meteor application, I have a File System collection of CSVs declared as shown below: Uploads = new FS.Collection("yourFileCollection", { stores: [new FS.Store.FileSystem("yourFileCollection", {path: "~/meteor_uploads"})] }); I am trying to iterate ...

Is the default behavior of Ctrl + C affected by catching SIGINT in NodeJS?

When I run my nodejs application on Windows, it displays ^C and goes back to the cmd prompt when I press Ctrl + C. However, I have included a SIGINT handler in my code as shown below: process.on('SIGINT', (code) => { console.log("Process term ...

Passport.js does not provide authentication for server-side asynchronous requests

Recently, I configured Passport.js with the local-strategy on my express server. Interestingly, when I am logged in and send an asynchronous request within NextJS's getInitialProps, it allows the GET request through client-side rendering but not serv ...

The website appears to be experiencing technical difficulties as the complete content

Check out this website: The full page content is not displaying properly. The footer content seems to be hidden and only appears after refreshing multiple times. Can anyone diagnose if there might be an issue with the CSS or JavaScript? ...

Is there a way to stop the OnBlur event from being activated during a freeze in IE11?

I am currently working on an exam application built with React that needs to be compatible with IE11. Within this application, I have implemented an onblur event that triggers a popup alert and increments the user's lockCount in the database when the ...

Completing a Promise without invoking the 'then' method

As I work on developing a small API for the NPM module Poolio, one common dilemma arises regarding error-first callbacks and promises. The challenge lies in how to cater to both types of asynchronous functions while maintaining consistency in APIs and retu ...

receiving a json object as opposed to a json array in php

Looking to get the output of json_encode() as an array, like so: [ { "url":"http://localhost/.....", "name":"abc" }, { "url":"http://localhost/.....", "name":"xyz" }, ] However, currently the result is in object format ...

Dividing a collection of URLs into smaller chunks for efficient fetching in Angular2 using RxJS

Currently, I am using Angular 2.4.8 to fetch a collection of URLs (dozens of them) all at once. However, the server often struggles to handle so many requests simultaneously. Here is the current code snippet: let collectionsRequests = Array.from(collectio ...

Top scenario and illustration of utilizing clusters in nodejs

I've been exploring the concept of clusters and I'm still a bit unclear about the most effective use-case scenario for them. Can anyone provide an example to help clarify this for me? ...

Animating SVGs in Internet Explorer (IE)

I'm currently working on an animation project using SVG images and JS, but unfortunately, I've run into a roadblock with SVG animations not functioning correctly in Internet Explorer. Do you happen to know of any solutions that could make it work ...

Generating an embedded object on the fly using an Angular Directive

After successfully establishing communication between the directive and controller, I am able to populate the embed code without any errors. However, the flash generated by the directive is not functioning at all, despite no visible discrepancies in the HT ...

Is there a resource available that can help me create a jquery/ajax image slider/carousel similar to this?

One thing that really caught my eye is how cnn.com has implemented this feature. I think it would be a great addition to the website I'm currently working on. I particularly like the page numbering, as well as the first, previous, next, and last butto ...