reorganizing groupby collection of objects using es6

I have received a data response that needs to be formatted as expected. I need to format an array of objects based on the rowIndex, and I am open to any better solutions.

Input :

productdata:[       { rowIndex:1 , columnKey:'productName'},
                    { rowIndex:1 , columnKey:'productID'},
                    { rowIndex:1 , columnKey:'productDate'},

                      { rowIndex:2 , columnKey:'productName'},
                    { rowIndex:2 , columnKey:'productID'},
                    { rowIndex:2 , columnKey:'productDate'},
                    ],

Expected Output:

[       { rowIndex:1 , columnKey:'productName'},
                    { rowIndex:1 , columnKey:'productID'},
                    { rowIndex:1 , columnKey:'productDate'}],
[{ rowIndex:2 , columnKey:'productName'},
{ rowIndex:2 , columnKey:'productID'},
{ rowIndex:2 , columnKey:'productDate'}],etc

Answer №1

To simplify creating an array, you can utilize the Array.prototype.reduce method.

const productData = [
  { rowIndex:1 , columnKey:'productName'},
  { rowIndex:1 , columnKey:'productID'},
  { rowIndex:1 , columnKey:'productDate'},
  { rowIndex:2 , columnKey:'productName'},
  { rowIndex:2 , columnKey:'productID'},
  { rowIndex:2 , columnKey:'productDate'},
];

const result = productData.reduce((acc, curr) => {
  const arrIndex = curr.rowIndex - 1;
  if (acc[arrIndex]) acc[arrIndex].push(curr);
  else acc[arrIndex] = [curr];
  return acc;
}, []);
console.log(result);

Answer №2

Have you considered trying this alternate approach utilizing the reduce method:

var productdata=[ { rowIndex:1 , columnKey:'productName'}, { rowIndex:1 , columnKey:'productID'}, { rowIndex:1 , columnKey:'productDate'}, { rowIndex:2 , columnKey:'productName'}, { rowIndex:2 , columnKey:'productID'}, { rowIndex:2 , columnKey:'productDate'}];

var result = Object.values(productdata.reduce((acc, elem)=>{
   acc[elem.rowIndex] = acc[elem.rowIndex] || [];
   acc[elem.rowIndex].push(elem);
   return acc;
},{}));

console.log(result);

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

Oops! It seems like there's a problem with reading the 'strEmail' property of undefined. Do you have any ideas on how to fix this issue

Currently, I am working with Express.js to create a straightforward login post request. Here is the code snippet: app.post("/login", (req, res) => { res.send( { isUserRegistered: userLogin(req.body.strEmail, req.body.strPassword), ...

Instructions on incorporating a logical condition for an object that is entering a region in motion

I am currently in the process of developing a new game concept. The goal of the game is to maneuver a square across the screen while avoiding raindrops that fall from the top of the canvas. I need assistance with programming the logic so that when a rain ...

The PageMethods function is successful when using a single parameter, but encounters an error when attempting to use two parameters, resulting in the

PageMethods worked perfectly when sending a single parameter to a code-behind aspx page. However, I encountered the error "Unknown web method" when attempting to provide two parameters (or an Object other than a String). The functional code in my aspx pag ...

Curved Edges Ensure Non-Interactive Elements

element, there is a query about utilizing a color wheel from a repository on GitHub. The goal is to disable any actions when clicking outside of the canvas border radius in this color wheel. Various steps need to be taken to prevent unwanted outcomes: - S ...

Ensure that a synchronous action is performed prior to each Backbone HTTP request

For each authenticated request (GET, POST, etc) in my Backbone/Marionette application, it is necessary to include an accessToken. The accessToken and expireDate are stored in the localStorage. To verify if the accessToken has expired, I utilize the metho ...

Retrieve all objects of the selected value using Angular autocomplete when an option is selected

I am currently working with an autocomplete component. I am passing an array of objects and would like to retrieve all item information (option) when an option is selected, not just the field value (option.name). <form class="example-form"> ...

What is the function of this program created with three.js?

I've been searching through various resources but I couldn't find any information on this new capsule. Although I understand the basics - that it creates a new capsule - I'm still unsure about the specific inputs required for it. Could someo ...

Organizing a JSON array and displaying it using the $.each function

My JSON array is structured like this: "series": [{ "book": 1, "chapter": 1, "title": "Title of this chapter", }, { "book": 1, "chapter": 2, "title": "Title of this chapter", }, { "bo ...

Avoid using `object` as a data type, as it can be challenging to work with

const useSetState = <T extends dataStructure>( initialState: T = {} as T ): [T, (patch: Partial<T> | ((prevState: T) => Partial<T>)) => void] => { const [state, setState] = useState<T>(initialState); const setMergeSta ...

React Redux - There is an error during rendering as expected props have not been received yet

After retrieving data from an API and storing it in the Redux state, I utilize a helper function within mapStateToProps to filter and modify a portion of that data before passing it along as props. Although everything appears to be functioning correctly b ...

Using Angular to retrieve data from a JSON file correlating with information in another JSON file

Just starting out with angular and facing a problem where I'm unsure of the best approach to setting up this code efficiently. I have 2 JSON files: images.json { "imageName": "example.jpg", "imageTags": ["fun","work","utility" ...

Oops! The Element Type provided is not valid - it should be a string

I have a desire to transition from using Victory Native to Victory Native XL. However, I am encountering an error message saying Render Error Element type is invalid. import * as React from "react"; import { View } from "react-native"; ...

Tips for storing information in a JSON document?

I'm looking to save JSON data as a file with the extension .json by converting an object into a string using JSON.stringify This is what my code currently looks like: const jsonObject: object = { 'countryName': 'Switzerland&apos ...

Logging to the console using an If/Else statement, with the Else block containing code that

I'm encountering a peculiar issue with my If statement. I'm modifying the state (true/false) of an object based on onMouseEnter and onMouseLeave. I can execute the code when it's true, but if I include any code in the else statement, it ma ...

Using React to iterate through a map and render various components

There's a unique scenario I'm facing, In my current environment, I don't have a standard list structure that allows me to map through and display components in each iteration, like this: list.map(shape => <Shape {...shape} />) In ...

What is the best way to prevent the content within a div from being obscured by a sticky element affixed to the bottom of the div?

I am struggling with ensuring that the content in my wrapper does not get cut off by the "view more" div attached to the bottom. The default wrapper cuts off the children, and even when expanded, the issue persists due to CSS problems. In React, the gener ...

Tips for incorporating nonce or sha into the connect-src directive in Content Security Policy (CSP)

Can a nonce be used in an API request to make sure that the connect-src in CSP doesn't flag it as a malicious address? It appears that nonce can only be used in script-src or style-src, not in connect-src. So far, I have only been able to list URLs ...

Unable to display nested objects retrieved from a JSON API in Angular

How can I retrieve images from an API and properly access the specific object within the object? Any tips would be greatly appreciated! API Endpoint: This is how my interface is structured: export interface MovieModel { id: number; name: string; ...

A method for enabling mat-spinner's entrance animation

I have recently implemented an Angular Material spinner with a disappearing animation that moves downwards before fading away. Is there a way to disable this animation? I have already tried using keyframes without success. <mat-spinner style="margin: ...

html displaying dynamic data in a table

As a beginner in coding, I am attempting to create a dynamic table. The first column is working fine with each new cell being added to the top. However, when I try to add columns, they fill from top to bottom instead of mirroring the first column. I want m ...