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

Display my additional HTML content on the current page

Is it possible for my addon to open a predefined html page in the current window when it is started? And if so, how can this be achieved? Currently, I am able to open my addon page in a new window using the following command: bridge.boot = function() { ...

Troubleshooting a Vue 2 component's prop receiving an incorrect value

I'm currently working on creating a menu that navigates between categories. When a category has a sub-category, it should return a boolean value indicating whether it has a sub-category or not. <template> <select><slot></slot ...

Images displayed alongside webpage contents

I'm having trouble getting these photos to display in the same row. Any suggestions on what I should change? https://i.stack.imgur.com/EbvmR.png I've attempted using float left and other commands, but one picture continues to stay in the lower r ...

Error message in Linux for NodeJS global NPM package: "File or directory does not exist"

After setting up my Ubuntu 14.04 system, I installed nodejs and npm using the command: sudo apt-get install nodejs npm To ensure packages utilize the node interpreter instead of nodejs, I created a symlink with: sudo ln -s /usr/bin/nodejs /usr/local/bin ...

Invoking an express route using JavaScript

After successfully defining some routes, including a text input search field at the top of the page, I created a listener function as shown below: $('#tags').keypress(function(e) { if (e.keyCode == 13 && document.getElementById('t ...

Switch the background color of a list item according to a JSON search

Our organization is in need of a feature where members can be inputted into a field and the background color of the parent list item changes based on the name lookup in a JSON file. We are open to a jQuery solution, but JavaScript will also work! You can ...

Instructions on generating a fresh Ethereum or Solidity contract for every test using JavaScript and Truffle

overview After developing an Ethereum smart contract using the Solidity language, I utilized Ganache to deploy my contract for testing purposes. However, in order to conduct tests effectively, I need to create a new instance of my contract using JavaScrip ...

Displaying a single row of a PHP array in bold formatting

I have a MySQL query result showing user information and subjects they have chosen. I want to highlight one specific row by making it bold using PHP while keeping the rest as regular text. How can I achieve this? $resultSet = $db->query ("...my q ...

Ensure that the assistant stays beneath the cursor while moving it

I am currently working on creating a functionality similar to the 'Sortable Widget', but due to some constraints, I cannot use the premade widget. Instead, I am trying to replicate its features using draggable and droppable elements: $(".Element ...

Is there a way to handle button click event when utilizing this.props.children in React?

I have recently completed a React component that serves as a modal wrapper. The content for this modal is passed through the props.children property. Inside the content, there is a button that, when clicked, should trigger an event in the parent component. ...

What is the reasoning behind the return type of void for Window.open()?

There is a difference in functionality between javascript and GWT in this scenario: var newWindow = window.open(...) In GWT (specifically version 1.5, not sure about later versions), the equivalent code does not work: Window window = Window.open("", "", ...

Retrieve SQL data and store it in a JavaScript variable

Need assistance with fetching data from SQL and storing it in a JavaScript variable. I have already connected PHPMyAdmin to my website. I am attempting to retrieve two variables (date) from my SQL table. JAVASCRIPT: var countdown_48 = new Date; countdow ...

Simplified jQuery function for multiple div mouseover operations

Uncertain about the accuracy of my title. Due to certain reasons, I need to assign different IDs for the class, as it only detects ID and not class when hovered over. Therefore, I have created a CSS version where the opacity of a specific div will change t ...

Tips for including a currency symbol before an input field using Material UI

Trying to add a dollar sign to the left of an input field using InputAdornment but it's not displaying correctly. Check out my code here: https://codesandbox.io/s/material-demo-wnei9?file=/demo.js ...

Custom JSON filtering

I have a JSON object called Menu which contains various menu items for my system that I am developing using VueJS + Vuetify. I need to filter these menu items based on the "text" field, regardless of position in the text and without differentiating between ...

Utilizing Angular partials within specific views with the assistance of ui-router

I am currently working on developing a MEAN application and facing some challenges while handling ui-router. Within my index.html file, I have set up the template for the entire website including a header, sidebar, and content area where I have placed < ...

Exploring Vue.js3: Simplifying Nested Array Filtering

Currently, I am in the process of sifting through an Array that contains nested arrays. To handle this task, I utilized computed and crafted a function called filteredEgg(). However, I seem to be overlooking something, as I'm only returning the main ...

Does type conversion have a specific ranking of preference?

When working with JavaScript, it's important to note that the language automatically converts types when necessary. For instance, if you have an expression like "8" * "3", JavaScript will convert the strings to numbers and calculate the result as 24. ...

AngularJS - how to dynamically delete a directive from an element

Looking for a way to dynamically add or remove directives from compiled and linked elements? I have a page with numerous inputs and want to disable all of them if a specific flag is set. The conventional method using jQuery's element.prop('disabl ...

Transform the characters within a string into corresponding numerical values, calculate the total sum, and finally display both the sum and the original string

I'm looking to convert a string containing a name into numerical values for each character, ultimately finding the sum of all characters' numerical values. Currently, only the first character's value is being summed using .charAt(). To achie ...