Locate items that possess identical property values and append them to a new array as a property

I am dealing with an array containing objects that have a specific property called "operationGroup" with the sub-property "groupId". Here is an example of the array structure:

[{
    operation: 11111,
    operationGroup: null
  },
  {
    operation: 22222,
    operationGroup: {
      groupId: 20
    }
  },
  {
    operation: 33333,
    operationGroup: {
      groupId: 1
    }
  },
  {
    operation: 44444,
    operationGroup: {
      groupId: 20
    }
  }
]

I need to identify all objects sharing the same groupId and then group them together in a new array property (groupedOperations) within each object. However, this should not be done if the operationGroup is null or if only one groupId is present. The desired output can be seen below:

[{
    operation: 11111,
    operationGroup: null
  },
  {
    operation: 22222,
    operationGroup: {
      groupId: 20
    },
    groupedOperations: [{
      operation: 22222,
      operationGroup: {
        groupId: 20
      },
      {
        operation: 44444,
        operationGroup: {
          groupId: 20
        }
      }
    }]
  },
  {
    operation: 33333,
    operationGroup: {
      groupId: 1
    }
  },
  {
    operation: 44444,
    operationGroup: {
      groupId: 20
    },
    groupedOperations: [{
        operation: 44444,
        operationGroup: {
          groupId: 20
        }
      },
      {
        operation: 22222,
        operationGroup: {
          groupId: 20
        },
      }
    ]
  }
]

Answer №1

let operationArray= [{
    code: 11111,
    groupCode: null
  },
  {
    code: 22222,
    groupCode: {
      groupId: 20
    }
  },
  {
    code: 33333,
    groupCode: {
      groupId: 1
    }
  },
  {
    code: 44444,
    groupCode: {
      groupId: 20
    }
  }
]
let groups = {}
let groupedOperations = []
for (let operation of operationArray) {
    if (!operation.groupCode) continue;
    if (!groups[operation.groupCode.groupId]) groups[operation.groupCode.groupId] = [];
    groups[operation.groupCode.groupId].push(operation)
}

for(let operation of operationArray){
    if(operation.groupCode && groups[operation.groupCode.groupId].length >= 2 ){
        operation.groupedOperations = groups[operation.groupCode.groupId]
    }
    groupedOperations.push(operation)
}
console.log(groupedOperations,groups)

Filter and categorize all operations based on groupID first. Then go through the request data again to update the groupedOperations property.

Answer №2

const data = [{
    id: 11111,
    category: null
  },
  {
    id: 22222,
    category: {
      groupId: 20
    }
  },
  {
    id: 33333,
    category: {
      groupId: 1
    }
  },
  {
    id: 44444,
    category: {
      groupId: 20
    }
  }
];

const groupedById =  data.reduce((accumulator, item) => { 
    if(item.category !== null) {
        let groupId = item.category.groupId; 
        if(!accumulator[groupId]){
            accumulator[groupId] = [];
        }
        accumulator[groupId].push(item); 
    }
    return accumulator;
}, {});

data.map(item => {
    if(item.category !== null) {
        let groupId = item.category.groupId;
        if(groupedById[groupId] && groupedById[groupId].length > 1){            
            item["groupedItems"] = groupedById[groupId];          
        }
    }
});

console.log(data);

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

Managing dynamic input texts in React JS without using name properties with a single onChange function

Dealing with multiple onChange events without a predefined name property has been challenging. Currently, one text input controls all inputs. I have come across examples with static inputs or single input functionality, but nothing specifically addressin ...

What are some ways I can improve the readability of this if-else function in Javascript ES6?

As a newcomer to React development, I am currently in the process of tidying up my code. One issue that I am facing is how to deal with a particular function while minimizing the use of if-else statements. const calculatePerPage = () => { if ...

Link to download an Excel spreadsheet

My server is capable of generating excel files dynamically, and I am utilizing AJAX to download these dynamic excel files. Upon successful completion in the callback function, I receive the data for the excel file. $.ajax({ url: exporting. ...

exploring the similarities between arrays containing nested objects

Can you assist me, please? I need help comparing and calculating the percentage difference between values and returning an array. I have to compare arrays, access objects with names and values, and calculate the percentage. For instance, if the first ite ...

HTML- Any suggestions on how to troubleshoot my sticky navbar not functioning properly?

I'm having trouble creating a sticky navbar. I've attempted to use z-index: 999 but it's not behaving as expected. * { margin: 0; padding: 0; } .navbar { display: flex; align-items: center; justify-items: center; position: ...

Determine the maximum value between an integer variable and an array

I need help finding a way to compare an integer value with an array and extract the cell that has a higher value than mine. For example: var array_score_specs = ["17", "24", "33", "46", "68", "128"]; var myValue = 25; var testValue = 0; for(let i = 0; i ...

Troubleshooting the malfunction of jQuery's change() function

There are three HTML select tags on my page. I want these three select tags to function as follows: When I change selectA, selectB should automatically update based on the selection in selectA. Similarly, when an option in selectB is created, changing se ...

React.js experiencing issues with loading the splash screen

I am developing a Progressive Web App (PWA) and I am currently facing an issue with displaying the splash screen. In my index.html file, I have added the following code to the head section: <link rel="apple-touch-startup-image" media="scr ...

Pass data to all routes in ExpressJS

After logging in, I am setting req.session variables as follows: req.session.loggedin = true req.session.firstname = loginDetails.firstName; I would like to streamline this process and pass this information to ALL routes without manually adding them to ea ...

`The error "mockResolvedValue is not recognized as a function when using partial mocks in Jest with Typescript

Currently, I am attempting to partially mock a module and customize the return value for the mocked method in specific tests. An error is being thrown by Jest: The error message states: "mockedEDSM.getSystemValue.mockResolvedValue is not a function TypeEr ...

What is the method for determining the height of a div element when it is set to 'height=auto'?

I am trying to determine the height of a specific div using Javascript. Here is the script I have written: function getMainDivHeight() { var num = document.getElementById('up_container').style.height; return num; } However, this script ...

Utilizing npm packages with grunt: A guide

Initially, when I was working with node.js without grunt, I simply had to write the code below to import an external module. var express = require('express'); However, after transitioning to grunt, I attempted to utilize the qr-image module in ...

How can I retrieve a password entered in a Material UI Textfield?

My code is functioning properly, but I would like to enhance it by adding an option for users to view the password they are typing. Is there a way to implement this feature? const [email, setEmail] = useState(''); const [password, setPassword] = ...

Supply a JSON parameter as a variable into the .load() function

When a button is clicked, I am attempting to load a page using the .load() method with a POST request. The URL parameters are generated and displayed as JSON formatted in the button attribute btn-url. Problem: The parameter is not being passed to the .loa ...

The Art of Validating Forms in Vue.js

Currently I am in the process of developing a form with validation using Vue, however, I've run into some errors that are showing up as not defined even though they are currently defined. HTML <form class="add-comment custom-form" @submit="checkF ...

What is the best way to stop this Jquery slider from moving?

I've been struggling with this issue for what feels like forever, and it's driving me crazy! I have a slider on the homepage that I'm trying to enhance with a "click to pause" feature (and maybe even a click to resume, for good measure). I ...

Overwriting Resolved Data in Angular UI-Router Child States

I'm facing an issue where the resolve function is the same in both parent and child states, but I need it to return different values based on the child state. Instead of customizing the implementation for each state, it seems to be inheriting the beha ...

What other choices are available for the Angular ui-select2 directive?

Within the Angular select2 controller below: <select ui-select2 id="projectListSelection" data-placeholder="Select a Project ..." ng-model="selectedProject"> @*ng-options="project.WebsiteName for project in projectList"*@ ...

Stop the jQuery custom slide animation when there are no more items to display

I have designed a unique slider for users to view the work process https://i.sstatic.net/FLYne.png When a user clicks the button, the slider will move left or right depending on the button clicked. However, if the user clicks multiple times, the slider ma ...

Dealing with AngularJS ng-model problems when duplicating a form

Currently, I am facing an issue with sending parameters to control and require some guidance. I have multiple types of questions within the ng-repeat loop named 'question' that I am iterating through. The problem arises when there are two questi ...