Condense an array of objects that contain another array by grouping them based on the objects' names

I have an array of JavaScript Objects. Each object contains an array data, which is the main focus here. My goal is to aggregate all arrays with the same name across different objects (the ids are not important for this process as I intend to visualize the data in a chart later).

norm.series = [
{ id: "qah01", name: "Bingo", data: [ ["date1", 1.5] ] },
{ id: "qah02", name: "Combo", data: [ ["date2", 2.5] ] },
{id: "qah03", name: "Bingo", data: [ ["date1", 0.5], ["date3", 1.2], ["date4", 2.0] ] }, 
{ id: "qah04", name: "Sango", data: [ ["date7", 3.2], ["date8", 2.8] ] }
]

What I am trying to achieve:

norm.series [
{ id: "qah01", name: "Bingo", data: [ [date1, 2.0], [date3, 1.2], [date4, 2.0] ] },
{ id: "qah02", name: "Combo", data: [ [date2, 2.5] ] },
{ id: "qah04", name: "Sango", data: [ [date7, 3.2], [date8, 2.8] ] }
]

This is my current progress:

const result = norm.series.reduce((acc, d) => {
    const found = acc.find((a, index) => a.data[index][0] === d.data[index][0]);
    const newData = a.data[index][1] + d.data[index][1];
    if (!found) {
       acc.push({id: d.id, name:d.name, data: d.data})
    }
    else {
       found.data.push(newData);
    }
    return acc;
}, []);

Answer №1

If you're looking to achieve the desired outcome, utilizing the `Array.reduce` method is the way to go. By harnessing the power of `Array.reduce`, you can efficiently pinpoint the matching value with `Array.findIndex` and create a suitable handler for it.

const values = [
  { id: "abc01", name: "Alpha", data: [ [ 'date1', 1 ] ] },
  { id: "def02", name: "Delta", data: [ [ 'date2', 2 ] ] },
  { id: "ghi03", name: "Gamma", data: [ [ 'date1', 3 ], [ 'date3', 1 ], [ 'date4', 2 ] ],
    { id: "jkl04", name: "Beta", data: [ [ 'date7', 3 ], [ 'date8', 6 ] ] }
];

const finalResult = values.reduce((acc, current) => {
  const matchIndex = acc.findIndex(({ name }) => name === current.name);
  if (matchIndex >= 0) {
    acc[matchIndex].data = acc[matchIndex].data.concat(current.data).reduce((total, currentVal) => {
      const dataIndex = total.findIndex(([dateName, dateValue]) => dateName === currentVal[0]);
      if (dataIndex >= 0) {
        total[dataIndex][1] += currentVal[1];
        return total;
      } else {
        return [ ...total, currentVal ];
      }
    }, []);
    return acc;
  } else {
    return [ ...acc, current ];
  }
}, []);

console.log(finalResult);

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

Steps to combine an array with a table (Linking the array ID with the table ID)

After running a query using DB::Select and raw SQL on a database list with user_id attached to items, I encountered an issue. The relationship between the user_id and the actual user was lost in the grouped count query I performed. Despite attempting a jo ...

Unable to add JSON data to Javascript List Object? Consider using a combination of Node.JS and Firebase for a

router.get('/getMeals',function(req,res){ var mealsList = []; mealsList.push("bar"); mealsRef.on("value",function(data){ data.forEach(function(child){ console.log(child.val()); var newMeal = child ...

Ways to conceal and reveal an item within a three.js environment

In my scene, I have an object made up of spheres and a hide/show button. The process in my program goes like this: when I choose one of the spheres using raycasting and then press the hide button, that particular sphere becomes hidden. Clicking on the sh ...

How can I modify the base color of a cone in Three.js?

My cone in the jsfiddle link is currently all blue, but I want to change the color of the square base to red. To do that, I need to alter the color of the two faces that make up the square base. How can this be achieved? View my cone on JsFiddle: http://j ...

Caution: An invalid next.config.js file has been detected while running the Next.js project

Whenever I try to run my project, I encounter the following three warnings: 1- warn - We found some invalid options in your next.config.js file. The property webpack5 is not recognized and may cause issues (allowed properties are: amp, analyticsId, assetP ...

The message "In Angular, there is no such property as 'data' in the type '{ user: User; session: Session; error: ApiError; }'."

Here is my complete supabase.service.ts code: import { Injectable } from "@angular/core"; import { createClient, SupabaseClient, User } from "@supabase/supabase-js"; import { BehaviorSubject } from "rxjs"; import { envi ...

What is the best way to organize React components that need to retrieve data from a modal?

At this moment, my React container is structured like so: class TableData extends Component { some React Functions and state changes. <Sidebar passdata as props/> } Within the Sidebar component, there is a modal that needs to update the state of b ...

Unable to eliminate the beforeunload event

The code below is used to display a default pop-up when the page is refreshed or closed: var myEvent = window.attachEvent || window.addEventListener; var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, ...

Removing an array of dynamic vectors

Could someone help me figure out why I'm encountering an error with the following code snippet? std::vector<double> *myVectorArr; myVectorArr = new std::vector<double>[10]; delete myVectorArr; The error message reads: munmap_chunk(): inva ...

What is the best way to style a value within a v-for loop inside an el-option element in Element UI?

I'm looking for a way to format the value in label(item.value) as a decimal within a v-for loop. Below is my code snippet: <el-form-item :label="label" :required="required" prop="Jan"> <el-select v-model=& ...

Retrieving HTML content from Wikipedia's API using JavaScript

I am encountering an issue where every time I attempt to log data to my console, an error occurs. Could someone kindly point out what may be the problem with the code? My objective is to actually showcase the html content on a webpage. Below is the code ...

Remove the carriage return and newline characters from a Python variable

After successfully obtaining the page source DOM of an external website, I found that it contained \r\n and significant amounts of white space. import urllib.request request = urllib.request.Request('http://example.com') response = ur ...

The jQuery selector is unable to locate the IMG element using its unique ID

I'm experiencing an issue with a webpage that includes the following code snippet: <img class="img-qrcode" id="img_123.000.00.01" src="http://localhost:7777/data/code_img\123.000.00.01.png" alt="./data/code_img\123.000.00.01. ...

What are the steps for examining array values using the IN operator?

I have a table with multiple arrays in each cell of the columns. COL1 COL2 row1: ('hi','hello') ('hi','hello') row2: ('hihi','below') ('pi','by') ...

Is it possible to refresh the dom without causing any disruptions to the Mouse Cursor?

Consider this function I'm currently utilizing: $('body').html( function(i,html) { var arr = html.split(". "); arr[arr.length-1]="<span class='findme' >"+arr[arr.length-1]+"</span>&nbsp;"; alert(arr) ...

Having trouble passing data from JavaScript to PHP with AJAX

I attempted to use AJAX to send data from an array (emp) and other string variables like 'gtotal' in my code, but the data did not transfer to the PHP file. Despite no errors being shown, when I removed the isset() function it displayed an error ...

The list marquee in HTML, JS, and CSS is not being properly rendered on

I recently made changes to a code that showcases a marquee scrolling a basic HTML list. Check it out here: I am facing 3 issues that I am struggling to resolve: JS: I want the marquee to continuously show text re-entering from the right just after it ...

Is it possible to contrast a specific character with an array of characters?

package loopPractice; import java.util.Scanner; public class ReplaceVowels { static Scanner scanner = new Scanner(System.in); public static void main(String[] arguments) { System.out.print("Enter a word: "); String input = scanner.nextLine(); ...

PHP - combine coordinates in an array to generate boundary values

In need of converting a range of 2 to 1000 latitude/longitude points (like all postal codes in a city) into one of two options: an array of lat/long values representing the perimeter formed by the points an array of lat/long values indicating high densit ...

I require the use of Nodejs with the gm module to process images, but it is essential that it

There are two methods to consider, but I am struggling to make it synchronous. Despite attempting to use Promise.all to synchronize the process, I am faced with the challenge of images processing asynchronously and inability to reject or resolve in a loop. ...