Is there a method to categorize an array of objects by a specific key and generate a new array of objects based on the grouping in JavaScript?

Suppose I have an array structured like this. It contains objects with different values but the same date.

[
    {
        "date": "2020-12-31T18:30:00.000Z",
        "value": 450
    },
    {
        "date": "2020-12-31T18:30:00.000Z",
        "value2": 362
    },
    {
        "date": "2020-12-31T18:30:00.000Z",
        "value3": 699
    },
    {
        "date"quot;: "2021-03-01T18:30:00.000Z",
        "value": 269
    },
    {
        "date"": "2021-03-01T18:30:00.000Z&",
        "value2": 450
    },
    {
        "date": "2021-03-02T18:30:00.000Z",
        "value3": 841
    },
    {
        "date": "2021-04-03T18:30:00.000Z",
        "value": 700
    }
]

My goal is to create a new array where the values with the same "date" are grouped together into one object.

[
    {
        "date": "2020-12-31T18:30:00.000Z",
        "value": 450,
        "value2": 362,
        "value3": 699
    },
    {
         "date": "2021-03-01T18:30:00.000Z",
         "value": 269,
         "value2": 450
     },
     {
          "date": "2021-03-02T18:30:00.000Z",
          "value3": 841
      },
      {
           "date": "2021-04-03T18:30:00.000Z",
           "value": 700
       }
]

Answer №1

If you want to efficiently achieve the desired outcome, you can leverage the power of Map and reduce

const data = [
  {
    date: "2020-12-31T18:30:00.000Z",
    value: 450,
  },
  {
    date: "2020-12-31T18:30:00.000Z",
    value2: 362,
  },
  {
    date: "2020-12-31T18:30:00.000Z",
    value3: 699,
  },
  {
    date: "2021-03-01T18:30:00.000Z",
    value: 269,
  },
  {
    date: "2021-03-01T18:30:00.000Z",
    value2: 450,
  },
  {
    date: "2021-03-02T18:30:00.000Z",
    value3: 841,
  },
  {
    date: "2021-04-03T18:30:00.000Z",
    value: 700,
  },
];

const dictionary = data.reduce((accumulator, current) => {
  const { date, ...rest } = current;
  if (!accumulator.has(date)) {
    accumulator.set(date, current);
  } else {
    const existingData = accumulator.get(current.date);
    Object.entries(current).forEach(([key, value]) => (existingData[key] = value));
  }
  return accumulator;
}, new Map());

const finalResult = [...dictionary.values()];

console.log(finalResult);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */

.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}

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

Having an issue with my JavaScript burger menu not functioning properly

I'm really struggling to figure out why my code isn't working. I've checked and rechecked all the links, and everything seems correct. Could it possibly be because the code is outdated? I've been stuck on this for two days now and can&a ...

Top recommendation for storing an unspecified number of structs in an array

Question at Hand Imagine a scenario where we have a struct defined as follows: struct MyStruct { enum Type { NONE, TYPE1, TYPE2 }; Type type; int value; } The application now requires storing an indefinite number of these structs in an array or si ...

Try out various scenarios using propsdata within Vue.js

In my component, there's a button that is displayed only when an article.link prop is not empty. I need to write a test to verify if the button is rendered when article.link has a value and another test for when it is empty. a.btn.plutus_btn-primary. ...

Angular tabs display the initial tab

I attempted to implement the Tabs feature from angular material by following the provided documentation. However, I encountered an issue where the first tab does not display upon page load; I have to manually click on it to view its content. For more info ...

Exploring the power of nested loops within an AJAX call in Angular

I have been attempting to iterate through a variable, search for IDs, and then make an ajax call to retrieve the detailed content of the different IDs. In the Success function, I am trying to loop through the received content and extract the emails. While ...

When utilizing the Angular 2 Stack, the Typescript Reflect.getMetadata('design:type'...) method may return an Object instead of a Date

When running the code sample below, it outputs "[Function: Date]", which is as expected. import 'reflect-metadata' function logType(target : any, key : string) { var t = Reflect.getMetadata("design:type", target, key); console.log(`${k ...

Creating a straightforward image slideshow using jQuery featuring next and previous buttons

I am looking for assistance in adding next and previous buttons to this slider. I came across a code snippet on a blog that could be useful, which can be found at .net/dk5sy93d/ ...

Next.js: An absence of response is observed when a high volume of requests is made on a server-side rendering page with

Currently, I am utilizing Next.js along with a custom server (express js) as demonstrated in the GitHub example. For instance, I have a page located at “/post/[id]” that makes use of Next.js dynamic routing. The issue arises when the number of request ...

Encountering difficulties reaching $refs within component method

Trying to access a ref defined within a template when an element is clicked. Here's the HTML: <!DOCTYPE html> <html lang="en"> <head> <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protectio ...

What are the best strategies for utilizing AnimatePresence for smooth and seamless transitions?

In my upcoming app, I am working on creating a seamless entry/exit animation using Framer Motion's AnimatePresence component. While experimenting with the delay feature, I encountered an issue where only one component would animate properly, while the ...

Error encountered when attempting to utilize Path Aliases in Angular 11.tsconfig

Currently, I am working on a project using Angular 11 and aiming to utilize short imports like import {smthg} from '@common' instead of import {smthg} from '../../../common' However, I keep encountering errors in IDEA: TS2307: Cannot f ...

Tips for implementing and utilizing an optional parameter within Vue Router

I am trying to set up a route for a specific component that can be accessed in two ways - one with a parameter and one without. I have been looking into optional parameters but haven't found much information. Here is my current route setup: { pa ...

unable to retrieve the value of the table row with a particular class designation

I'm currently working with a table code and I need to retrieve the value of the table row with the class "highlight". However, when trying to do so with the code below, I'm getting a null result. Can someone please assist me? Table name: itemtab ...

"Using TypeScript: How to effectively wait for the completion of the array.sort

Need to implement a loading screen in Angular until an array is sorted. Solution provided below: this.isSorting = true; this.array = this.array.sort((a,b) => a.totlaTime - b.totalTime); this.isSorting = false; The issue faced is when isSorting is set t ...

Newbie to Next-JS exploring the use of two dynamic APIs, with successful integration of one while encountering difficulties with the other

I recently received help from a friend to transform my inefficient JS web app into a next-app. However, as I attempted to progress further, I encountered various obstacles and found myself feeling lost. Within my project, I have developed two APIs that fe ...

Using PHP script, extract information from a JSON file and populate a dropdown menu in HTML

I am attempting to extract data from a JSON file using PHP and then display this data in an HTML select tag on the front end. Below is my PHP file: <?php ini_set('display-errors', 'on'); error_reporting(E_ALL); $executionStartTim ...

Is there a way to verify if a React hook can be executed without triggering any console errors?

Is there a way to verify if a React hook can be invoked without generating errors in the console? For example, if I attempt: useEffect(() => { try { useState(); } catch {} }) I still receive this error message: Warning: Do not call Hooks i ...

Ways to display additional information in typeahead using Angular JS

Currently, I am using the Bootstrap directory typeahead in Angular. I am looking to display more results in my HTML template instead of just the name: typeahead="job as job.name for job in getJobPlace($viewValue) | filter:{name:$viewValue}" I would like ...

Remove any repeated elements within a collection of arrays containing integers

In a scenario where we have a collection of integer arrays like the following: List<int[]> intArrList = new List<int[]>(); intArrList.Add(new int[3] { 0, 0, 0 }); intArrList.Add(new int[5] { 20, 30, 10, 4, 6 }); intArrList.Add(new int[3] { 1, ...

What distinguishes ES6 from ES2015 in the TypeScript compiler option `--libs`?

Can you explain the distinction between ES6 and ES2015 in the TypeScript compiler option here? Also, what does --libs do? ...