Create an array by grouping objects together using a specific key to form a new array object

Here is my array object:

[{ role : 'Role 1', name: 'A', slid: 'a'}, {role : 'Role 1', name: 'B',slid: 'b'}, {role : 'Role 2', name: 'X', slid: 'x'}, {role : 'Role 2',name: 'Y', slid: 'y'},{role : 'Role 3',name: 'Z',slid: 'z'}]

Is there a way to merge the objects in this array based on their roles and create new array objects in the following format?

[{role : 'Role 1', list: [{name: 'A', slid: 'a'}, {name: 'B', slid: 'b'}]},
 {role : 'Role 2', list: [{name: 'X, slid: 'x'}, {name: 'Y', slid: 'y'}]},
 {role : 'Role 3', list: [{name: 'Z', slid: 'z'}]}]

I have searched through various examples, but haven't found a solution yet.

Answer №1

To organize the array into an object, utilize the reduce method. Then, transform the object back into an array using Object.values.

var data = [{"role":"Role 1","name":"A","slid":"a"},{"role":"Role 1","name":"B","slid":"b"},{"role":"Role 2","name":"X","slid":"x"},{"role":"Role 2","name":"Y","slid":"y"},{"role":"Role 3","name":"Z","slid":"z"}];

var finalResult = Object.values(data.reduce((collection, {role,...rest}) => {
  collection[role] = collection[role] || {role,list: []};
  collection[role].list.push(rest);
  return collection;
}, {}));

console.log(finalResult);

Answer №2

const list = [{
  role: 'Role 1',
  name: 'A',
  slid: 'a',
}, {
  role: 'Role 1',
  name: 'B',
  slid: 'b',
}, {
  role: 'Role 2',
  name: 'X',
  slid: 'x',
}, {
  role: 'Role 2',
  name: 'Y',
  slid: 'y',
}, {
  role: 'Role 3',
  name: 'Z',
  slid: 'z',
}];

// Iterating through the array elements
const result = list.reduce((temp, item) => {
  // Checking if the item's role is already in our final array
  const foundItem = temp.find(existingItem => existingItem.role === item.role);

  // Adding a new value to the existing role
  if (foundItem) {
    foundItem.list.push({
      name: item.name,
      slid: item.slid
    });

    return temp;
  }

  // Creating a new array element if role does not exist
  temp.push({
    role: item.role,
    
    list: [{
      name: item.name,
      slid: item.slid
    }],
  });
  
  return temp;
}, []);

console.log(result);

Answer №3

Introducing a unique method using Array.map

const data = [{ role : 'Role 1', name: 'A', slid: 'a'},{role : 'Role 1', name: 'B',slid: 'b'}, {role : 'Role 2', name: 'X', slid: 'x'}, {role : 'Role 2',name: 'Y', slid: 'y'},{role : 'Role 3',name: 'Z',slid: 'z'}]

const result = data.sort((a,b) => a.role.localeCompare(b.role))
                   .map(({ role, ...rest }) => ({ role, list: [rest] }))
                   .flatMap(({ role, list }, i, t) => 
                         role == (t[i+1] && t[i+1].role)
                           ? (t[i+1].list.unshift(list[0]), [])
                           : { role, list })

console.log(result)

Answer №4

To tackle the problem, one could utilize the reduce function

const data = [{ role : 'Role 1', name: 'A', slid: 'a'}, {role : 'Role 1', name: 'B',slid: 'b'}, {role : 'Role 2', name: 'X', slid: 'x'}, {role : 'Role 2',name: 'Y', slid: 'y'},{role : 'Role 3',name: 'Z',slid: 'z'}]

var groupBy = function(array, key) {
  return array.reduce(function(reducedValue, obj) {
    (reducedValue[obj[key]] = reducedValue[obj[key]] || []).push(obj);
    return reducedValue;
  }, {});
};

console.log(groupBy(data, 'role'));

//{Role 1: Array(2), Role 2: Array(2), Role 3: Array(1)}

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

The state object in Next.js appears to be missing

const [ values , setValues ] = React.useState({ input_type: '', elements: [] }) const addOption = () => { let newElements = values.elements newElements.push({ type: "option", ...

Steps to determine the number of columns with a zero value in a multidimensional array

Can you assist me in determining the number of COLUMNS that contain zeros within a multidimensional array? I have already figured out how to calculate the rows with zeros, but columns are giving me trouble. Any guidance would be appreciated. public clas ...

Monitor the collection for changes before adding an item to the collection

When using ui-select multiple, I am facing an issue where I need to check the collection before ng-model="collection" is updated in order to ensure that the new value is not already present in it. Simply watching the collection does not solve this problem ...

Steps to generate an error in the 'response' function of a $httpProvider interceptor

I am currently working on creating a custom HTTP interceptor in Angular and I am looking to generate an error from the response of the $httpProvider interceptor. According to the provided documentation: response: Interceptors are triggered by the http re ...

error is not defined in the onsuccess function of the ajax.beginform partial view

Currently, I am working on an MVC5 project where a View is calling a Partial View. Within the Partial View, there is an Ajax.BeginForm that triggers a function on OnSuccess. However, during execution, I encounter an error stating that the function cannot ...

Developing a custom JavaScript function to iterate through a group of html elements

In my mission to create a function that loops through a set of HTML elements and gathers their values, I aim to then utilize those values to produce an HTML textarea. Thus far, I've established a series of HTML input boxes and a JavaScript function f ...

Tips for simulating an ajax request in a Jasmine test

Check out my code snippet below: function sendRequestData(url, urlParameters) { $.ajax({ url : url, method : 'POST', headers : { 'Accept' : 'application/json' }, contentType : 'application/js ...

What could be causing this floating point exception I am experiencing?

I encountered an issue with my program where everything was working fine when manually iterating over 5 individual variables. However, when I changed them to arrays and used a for loop, I started getting floating point exceptions. Despite my efforts to d ...

Swapping out the video in real-time using an on-demand script

Recently, I encountered an issue with my blog's YouTube video switcher. It seems that the videos won't play once they are changed, and it is related to a light YouTube embed script that I found here: . I believe this script was implemented to imp ...

Preserving and Reversing Drag and Drop Canvas Configurations in HTML5 Canvas

With the help of this innovative JS Fiddle, I have successfully created dynamic canvases and enabled the functionality to drag and drop images across multiple canvases. var next = 4 function addCanvas() { // create a new canvas element ...

Issue with wp_ajax function not being triggered in Wordpress

Attempting to implement my first AJAX Function in Wordpress 4.3. I created a plugin called "calipso". Within the plugin, there are two files: calipso.php : <?php /** * @package calipso * @version 1.0 */ /* Plugin Name: calipso Plugin URI: http://www. ...

Attempting to eliminate Roman numerals and numerical values from a list of Strings

In my quest to cleanse a text file of the story "Robin Hood", I am facing the challenge of eliminating elements such as "I.", "II.", "279" (page numbers and chapters), etc. The obstacle lies in removing these numerical values from the string arraylist. fo ...

Enhance the style of your React components with React-addons-css-transition

Currently, I am working on creating tabs in React JS and incorporating animations using React-addons-css-transition-group. The code snippet I have written for this purpose is as follows: render() { let view = this.state.tiresView ? this.renderTiresV ...

Utilizing setColumns() function within Google Charts for JSON data tables

Is there a feature in the Google Charts API that functions similar to setColumns() for working with JSON data? I'm aiming to reduce PHP calls by consolidating my data into a single array and then specifying which columns Google Charts should utilize. ...

Retrieve the 90 days leading up to the current date using JavaScript

I've been searching for a way to create an array of the 90 days before today, but I haven't found a solution on StackOverflow or Google. const now = new Date(); const daysBefore = now.setDate(priorDate.getDate() - 90); The result I'm looki ...

I'm having some trouble with my middleware test in Jest - what could be going wrong?

Below is the middleware function that needs testing: export default function validateReqBodyMiddleware(req: Request, res: Response, next: NextFunction) { const { name, email }: RequestBody = req.body; let errors: iError[] = []; if (!validator.isEmai ...

I'd like to know what sets next/router apart from next/navigation

Within Next.js, I've noticed that both next/router and next/navigation offer a useRouter() hook, each returning distinct objects. What is the reasoning behind having the same hook available in two separate routing packages within Next.js? ...

Using PHP, we can easily create an array and store values that are stored in variables

Hey, I currently have 2 variables set up. $firstVariable = "123"; $secondVariable = "321"; Both of these variables are dynamically calculated and subject to change based on varying circumstances. Now, I am looking to combine these values into a single ar ...

Ways to execute a JavaScript function upon a button click instead of during the page load completion

I searched on Google but couldn't find the answer, so I'm asking here for help. In the attached screenshot located at the end, when the user clicks on the download button, some backend actions are performed such as file transfer. Once the proces ...

React-Native has reached the maximum update depth, please check the new state

When I try to add and change the number (setNum(number+1)), I encounter an error message stating: Maximum update depth exceeded. This issue may arise when a component repetitively calls setState inside componentWillUpdate or componentDidUpdate. React enfor ...