Organize the array by property name and include a tally for each group

My current data structure looks like this:

var data = [
   { MainHeader: Header1, SubHeader: 'one'},
   { MainHeader: Header1, SubHeader: 'two'},
   { MainHeader: Header2, SubHeader: 'three'},
   { MainHeader: Header2, SubHeader: 'four'},
   { MainHeader: Header2, SubHeader: 'five'}
];

I am looking to transform it into the following format:

var groupheaders = [
  { startColName: 'one', numberofCols: 2, title: Header1},
  { startColName: 'three', numberofCols: 3, title: Header2}
];

Does anyone know of a graceful solution to achieve this using Lodash?

Answer №1

To streamline the process, consider using a mapping object where each MainHeader serves as a key. If a MainHeader is already present in the map, increment its count. Otherwise, add a new key with an associated object value.

Next, utilize the Object.values() function to extract the values into an array:

const data = [{MainHeader:"Header1",SubHeader:"one"},{MainHeader:"Header1",SubHeader:"two"},{MainHeader:"Header2",SubHeader:"three"},{MainHeader:"Header2",SubHeader:"four"},{MainHeader:"Header2",SubHeader:"five"}],
      map = {};

data.forEach(({ MainHeader, SubHeader }) => {
  if(map[MainHeader])
    map[MainHeader].numberofCols++
  else
    map[MainHeader] = { title: MainHeader, startColName: SubHeader, numberofCols: 1 };
})

let output = Object.values(map);

console.log(output)

For an ES5-compatible approach:

var data = [{MainHeader:"Header1",SubHeader:"one"},{MainHeader:"Header1",SubHeader:"two"},{MainHeader:"Header2",SubHeader:"three"},{MainHeader:"Header2",SubHeader:"four"},{MainHeader:"Header2",SubHeader:"five"}],
      map = {};

data.forEach(function(o) {
  if(map[o.MainHeader])
    map[o.MainHeader].numberofCols++
  else
    map[o.MainHeader] = { title: o.MainHeader, startColName: o.SubHeader, numberofCols: 1 };
})

var output = Object.keys(map).map(function(k) {
  return map[k];
});

console.log(output)

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

Calculate and retrieve the result from the event handling function

I need to capture a returned value and store it in a variable within an event handler function. Below is a sample code snippet demonstrating this: var xhr = new XMLHttpRequest(); function getData(e) { if (xhr.readyState === 4) { if (xhr.s ...

Css shaky letters transformation

[SOLUTION] To resolve this issue, you can utilize the will-change CSS property that enforces GPU rendering: will-change: transform; [ORIGINAL QUESTION] After extensive searching on the internet, I have yet to find a solution to a seemingly simple prob ...

Leveraging orWhere in the bookshelf JavaScript object

I encountered an issue while using bookshelf js to create a query. When implementing orWhere in the query, I received an error message. An error occurred stating 'Object has no method 'orWhere'." Below is the code snippet that led to thi ...

Convert an array to UTF-8 encoding and extract the values into a text input field

Having encountered a minor issue, I've successfully moved data from one file to another using Ajax with the help of echo in my query. However, I'm now attempting to utilize json_encode(); and facing some difficulties. Could someone please point o ...

Integrating a parameter into a plugin allows for displaying a specified number of elements in the output

A unique plugin is being used to create a vertical slideshow effect. This plugin scrolls the top-most div in a series of divs with the same class upwards, removes it from the container, and appends it to the bottom of the series within the container. The e ...

Conflicting Angular components: Sorting tables and dragging/dropping table rows

In the current project I'm working on, I've integrated both angular table-sort and angular drag-drop. However, I ran into an issue where dragging a row and attempting to drop it onto another row causes the table sort to forcefully rearrange the r ...

Using electron cookies in Angular involves integrating Electron's native cookie functionality into an

I am currently dealing with electron and looking to implement cookies conditionally in my project. If the application is built using electron, I want to utilize Electron Cookies; otherwise, I plan to use Angular Cookies. However, I'm encountering diff ...

What is the best way to retrieve a JSP parameter dynamically or how can one create a JSP parameter on the

Currently learning JSP and ajax simultaneously. In the process of creating a dynamic tab that can be added or removed using these steps. Looking to pass parameters from controller to the content area of the newly added tab. 1. When clicking on the &apos ...

Combining the functionality of a click event

Is it possible to combine these two functions in a way that ensures when '#css-menu' is shown, '.menu' becomes active, and vice versa? $('.menu').click(function() { $('#css-menu').toggleClass('shown hidden& ...

Swipe to eliminate an element in Ruby on Rails

I am looking to implement a drag-and-drop delete feature on my website, similar to the recycle bin/trash function on Windows or OSX. Within my database, I have multiple objects represented by div elements using Ruby. While I know how to add drag functiona ...

unable to establish connection due to port error in node.js

While executing node app.js I encountered the following error message info - socket.io started warn - error raised: Error: listen EACCES This snippet shows all the JavaScript code within the application. After running sudo supervisor app.js T ...

Invoke a Google Apps Script through AJAX that necessitates authentication

I am looking to access a Google Apps Script via AJAX that requires user authorization to send an email from their Gmail account. The challenge lies in the fact that I need to send the email from within the Google Apps Script. The call originates from my w ...

Tips for sending JSON data from JavaScript to PHP servers

After encoding an array into JSON using JavaScript, I set up my ajaxrequest object like this: var data = JSON.stringify(cVal); function ajaxRequest(url, method, data, asynch, responseHandler){ var request = new XMLHttpRequest(); request.open(meth ...

Passing data from a card component to a tab component in ReactJS

Just starting out with react and facing an issue. I want to transfer props from the child component to the parent component tabs that include favorite tabs. My plan was to pass the values through the handleClickOpen method where I click the favorites icon. ...

What is the best way to eliminate a specific element from a JavaScript array?

What is the best way to eliminate a particular value from an array? For example: array.exclude(value); Limitations: I must solely rely on pure JavaScript without any frameworks. ...

Generating HTML table rows dynamically in Angular based on the number of items stored in a $scope variable

In my current project, I am utilizing Angular to dynamically populate data in an HTML table. Instead of manually coding each row for display, I am in need of a solution that allows me to programmatically define each HTML row. The Angular controller snippet ...

Utilize moment.js to format a datetime and display the corresponding timezone

I'm having trouble displaying timezones correctly using moment.js. I attempted to use the following code: var result = moment(someDate).format("MM/DD/YYYY HH:mm A Z"); This returns something like: 08/05/2015 06:18 PM +02:00, which is okay, but I w ...

I wonder what the response would be to this particular inquiry

I recently had an angular interview and encountered this question. The interviewer inquired about the meaning of the following code snippet in Angular: code; <app-main [type]="text"></app-main> ...

The latest URL is not launching in a separate tab

Looking for some assistance with this code snippet: <b-btn variant="primary" class="btn-sm" :disabled="updatePending || !row.enabled" @click="changeState(row, row.dt ? 'activate' : 'start&apo ...

What is the proper way to send properties to a component that is enclosed within a Higher Order Component?

I have a situation where I need to pass props from the index page to a component wrapped inside two higher-order components. Despite fetching the data successfully in getStaticProps, when passing the props to the About component and console logging them in ...