What is the process of creating a new array by grouping data from an existing array based on their respective IDs?

Here is the initial array object that I have:

const data = [
   {
      "order_id":"ORDCUTHIUJ",
      "branch_code":"MVPA",
      "total_amt":199500,
      "product_details":[
         {
            "image":"CC252.jpg",
            "cate":"Mobile Accessories"
         }
      ]
   },
   {
      "order_id":"ORHOGFD79L",
      "branch_code":"PBVR",
      "total_amt":325880,
      "product_details":[
         {
            "image":"1617382086515.jpg",
            "cate":"Mobile Accessories"
         },
         {
            "image":"1617382322759.jpg",
            "cate":"Mobile Accessories"
         },
         {
            "image":"CC251.jpg",
            "cate":"Mobile Accessories"
         }
      ]
   },
   {
      "order_id":"ORIYDJLYSJ",
      "branch_code":"MVPA",
      "total_amt":1549500,
      "product_details":[
         {
            "image":"CC250.jpg",
            "cate":"Mobile Accessories"
         },
         {
            "image":"CC256.jpg",
            "cate":"Mobile Accessories"
         }
      ]
   }
]

My goal is to create a new array by grouping data with the same branch code under one object.

Desired Output:

const newData = 
[
  {
    MVPA: [
      {
        order_id: 'ORIYDJLYSJ',
        (otherdetails)
      },
      {
        order_id: 'ORDCUTHIUJ',
        (otherdetails)
      }
    ]
  },
  PBVR: [
    {
      order_id: 'ORHOGFD79L',
      (otherdetails)
    }
  ]

Any suggestions on how to achieve this in a scalable way considering the data could be much larger when fetched from a database?

Answer №1

One way to achieve this is by using the Array.reduce method.

data.reduce((obj, item) => (obj[item.branch_code] = [ ...(obj[item.branch_code] || []), item], obj), {})

Answer №2

Start by initializing an object that will store data based on branch codes.

const dataObject = data.reduce((map, obj) => {
     if(obj.branch_code in map){
       map[obj.branch_code].push({...obj});
     } else {
      map[obj.branch_code] = [{...obj}];
     }
    return map;
}, {});

This results in

{MVPA: Array(2), PBVR: Array(1)}

Next, iterate over the keys of the object created above to generate your desired array.

const finalArray = Object.keys(dataObject).map(key => ({[key]: [...dataObject[key]]}));

console.log('finalArray', finalArray);

This leads to

(2) [{…}, {…}]
0: {MVPA: Array(2)}
1: {PBVR: Array(1)}

Answer №3

const uniqueBranchCode = [...new Set(data.map(i => i.branch_code))] // Retrieving unique branch_codes

const newData = uniqueBranchCode
.map(order => data.filter(orderSpecific => orderSpecific.branch_code === order)) // Grouping elements by branch_code
.map(item => ({[item[0].branch_code]: item})) // Assigning key and returning grouped elements

const data = [
   {
      "order_id":"ORDCUTHIUJ",
      "branch_code":"MVPA",
      "total_amt":199500,
      "product_details":[
         {
            "image":"CC252.jpg",
            "cate":"Mobile Accessories"
         }
      ]
   },
   {
      "order_id":"ORHOGFD79L",
      "branch_code":"PBVR",
      "total_amt":325880,
      "product_details":[
         {
            "image":"1617382086515.jpg",
            "cate":"Mobile Accessories"
         },
         {
            "image":"1617382322759.jpg",
            "cate":"Mobile Accessories"
         },
         {
            "image":"CC251.jpg",
            "cate":"Mobile Accessories"
         }
      ]
   },
   {
      "order_id":"ORIYDJLYSJ",
      "branch_code":"MVPA",
      "total_amt":1549500,
      "product_details":[
         {
            "image":"CC250.jpg",
            "cate":"Mobile Accessories"
         },
         {
            "image":"CC256.jpg",
            "cate":"Mobile Accessories"
         }
      ]
   }
]

const uniqueBranchCode = [...new Set(data.map(i => i.branch_code))]

const newData = uniqueBranchCode
.map(order => data.filter(orderSpecific => orderSpecific.branch_code === order))
.map(item => ({[item[0].branch_code]: item}))

console.log(newData)

Answer №4

Give this method a try

const items = [{"order_id":"ORDCUTHIUJ","branch_code":"MVPA","total_amt":199500,"product_details":[{"image":"CC252.jpg","cate":"Mobile Accessories"}]},{"order_id":"ORHOGFD79L","branch_code":"PBVR","total_amt":325880,"product_details":[{"image":"1617382086515.jpg","cate":"Mobile Accessories"},{"image":"1617382322759.jpg","cate":"Mobile Accessories"},{"image":"CC251.jpg","cate":"Mobile Accessories"}]},{"order_id":"ORIYDJLYSJ","branch_code":"MVPA","total_amt":1549500,"product_details":[{"image":"CC250.jpg","cate":"Mobile Accessories"},{"image":"CC256.jpg","cate":"Mobile Accessories"}]}];

const updatedInfo = items.reduce((accumulator, {order_id, branch_code, product_details}) => {
  accumulator[branch_code] ??= {[branch_code]: []};
  accumulator[branch_code][branch_code].push({order_id, product_details});
  
  return accumulator;
}, {});

console.log(Object.values(updatedInfo));

Answer №5

let obj = {}

function analyzeData(input) {
const filteredData = data.filter(function (item) {
    return item.branch_code === input
})

return filteredData
}

for (let index = 0; index < data.length; index++) {
obj[`${data[index].branch_code}`] = analyzeData(data[index].branch_code)
}

console.log(obj)

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

"User-friendly Material-UI input field paired with a clear label

Seeking guidance on creating a text field with a label using the material-ui library. I am searching for something similar to this example: https://github.com/callemall/material-ui/blob/master/src/TextField/TextFieldLabel.jsx Unfortunately, I have been ...

Restrict the quantity of recommendations provided by the AutoComplete feature

After exploring the autocomplete API from https://material-ui.com/api/autocomplete/, I am unable to figure out a way, given my basic understanding of javascript, to restrict the display of a specific number of options beneath the TextField. I am working o ...

Is there a way to ensure that in React (Typescript), if a component receives one prop, it must also receive another prop?

For instance, consider a component that accepts the following props via an interface: interface InputProps { error?: boolean; errorText?: string; } const Input = ({error, errorText}: InputProps) => { etc etc } How can I ensure that when this com ...

Is there a way to transfer information from an ajax function to an express js server?

Is there a way to transfer data from a separate JS file to my Express.js server? I'm attempting to parse XML files using AJAX/jQuery and send the resulting data to an Express.js server. The parser is located in a different file within the /public/jav ...

How are jQuery.ajax and XMLHttpRequest different from each other?

My goal is to fetch and run the script contained in a file named "example.js" using an AJAX request. Suppose the content of example.js looks like this: const greetings = { hello: "Hello", goodBye: "Good bye" } console.log(greetings.hello) In anot ...

Troubleshooting: Resolving the error message 'Unable to assign to Partial<this>' within a subclass method

If I call the base class's update method using a subclass instance, it functions as expected. However, I encounter an error when attempting to do so within a subclass method: Argument of type '{ prop: number; }' is not compatible with par ...

Error message: "Receiving a 'TypeError' in Node.js async parallel - the task is not recognized as a

Currently, I am utilizing the async module to run multiple tasks simultaneously. In essence, I have two distinct files named dashboard.js and Run.js. Dashboard.js module.exports = { func1 : function(){ console.log(“Function one”); }, ...

Tips for integrating JavaScript libraries with TypeScript

I'm looking to add the 'react-keydown' module to my project, but I'm having trouble finding typings for it. Can someone guide me on how to integrate this module into my TypeScript project? ...

Converting objects into CSV format and exporting them using JavaScript

When exporting to CSV, large strings are causing other cells to be rewritten. See the screenshot for the result of the export here. For the code related to this issue, refer to this link. The question is how to prevent large string values in a cell from a ...

What could be the reason for the malfunctioning of the header() function in PHP

Currently, I'm utilizing AJAX to facilitate user registration for a service. Here's the code snippet for the submit button: <input type="button" id="register" name="register" class="btn btn-success" onclick="registration();" value="Register"/ ...

Tips for enabling custom object properties in Chrome DevTools

In my typescript class, I am utilizing a Proxy to intercept and dispatch on get and set operations. The functionality is working smoothly and I have successfully enabled auto-completion in vscode for these properties. However, when I switch to the chrome d ...

Reverse row changes in Angular Ag-Grid with the click of a button

Developed using Angular and JavaScript technologies. The AG-Grid consists of editable records with the first column being a checkbox. When changes are made to any selected records, clicking on a particular record's checkbox and then pressing a button ...

Is there a way to trigger an Axios response without repeated calls or the use of a button?

As I navigate my way through using react and Axios, I encountered an issue with a get request in my code. Currently, I have a button that triggers the request when clicked, but I want to eliminate the need for this button and instead have the information d ...

What is the approach to forming a Promise in TypeScript by employing a union type?

Thank you in advance for your help. I am new to TypeScript and I have encountered an issue with a piece of code. I am attempting to wrap a union type into a Promise and return it, but I am unsure how to do it correctly. export interface Bar { foo: number ...

Encountering an issue when trying to start npm in the command line interface

Here is the content of my package.json file: "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, This project was created using create-react-app. Ho ...

Utilize express/node to iterate through requests sent to the NOAA API

I have developed an API middleware for my company to pull information from the NOAA API and store it in my database. The process works as expected, but the challenge arises when trying to handle information based on zip codes one at a time. Each request fe ...

Utilizing Regex Patterns to Manipulate CSS Attributes

I am dealing with a string containing CSS properties and their values: str = "filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#cccccc', endColorstr='#000000'); background: -webkit-linear-gradient(top, black, wh ...

Is there a way to stop a for-in loop within a nested forEach function in JavaScript?

I am facing a situation with nested loops for (var key in params) { if (Array.isArray(params[key])) { params[key].every(function(item) { let value = something(item.start, item.end); if (value === item.start || value == item.end) { ...

Simulating dynamic route parameters in the Next 13 application directory

I am currently working with Jest and testing library to conduct unit tests on my NextJS application. I am facing difficulties in rendering a page on a dynamic path. Here is the code for my page/component: export default async function MyPage({ params }: { ...

Manipulating values in JavaScript using an onclick event in PHP

I am looking to remove the "http" from the URL part of an input link before sending the data. This is my input code that looks like this when clicked: <input style="outline: none;" type="button" onclick="formatText ('link:url');" class="btn ...