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

Generating unique names based on input from users

We are working with an array containing names and an input field where users can enter a string to receive name suggestions. The array includes names like Alex and Anna, and when the user types "a," we want to suggest these names. Below is the code snippet ...

Nested formArrays within formArrays in Angular 4

I've been working on implementing a FormArray inside another FormArray, but it doesn't seem to be functioning correctly. I also tried the solution provided in the link below, but it didn't work for me. How to get FormArrayName when the Form ...

NextJS reliably accesses the request object on each page

I'm currently working on setting up an authentication system using express, passport, and nextjs with OpenID Connect. The user data is stored in the request object using express-session, providing access to req.user in each request. My challenge now ...

Unable to retrieve data from MySQL Database using Express Route

Struggling to understand how to execute a MySQL database query within the promise in my route file. Currently, I am developing a RESTful API for interacting with a MySQL database using GET methods. The technologies being utilized are Express for the backen ...

Is it feasible to access a service instance within a parameter decorator in nest.js?

I am looking to replicate the functionality of Spring framework in nest.js with a similar code snippet like this: @Controller('/test') class TestController { @Get() get(@Principal() principal: Principal) { } } After spending countless ho ...

An npm list is always full of modules

As I prepare to install a package using npm, I noticed that my folder for the new project already has numerous items listed when I run npm list. Is it normal for the folder not to be empty at this stage? Have I made an error somewhere? ...

Issue with VueJS components not functioning as expected with routes

I've encountered an issue when using the component tag with an id of #app within the template of my components/App.vue file. Whenever I include this setup, I receive the following errors: // components/App.vue <template> <div id="app"> ...

Elegant transition effects for revealing and hiding content on hover

While customizing my WordPress theme, I discovered a unique feature on Mashable's website where the social buttons hide and show upon mouse hover. I'd love to implement this on my own site - any tips on how to achieve this effect? If you have ex ...

Typescript iterative declaration merging

My current project involves creating a redux-like library using TypeScript. Here is an example of the basic action structure: interface ActionBase { type: string; payload: any; } To customize actions for different types, I extend the base interface. ...

How can you access PHP $_GET values using JavaScript?

Recently, I encountered an issue with my app that is running on localhost/index.php. In my JavaScript code, I am using the History API as follows: history.replaceState({}, null, "?uid=" + uid); to update the URL of the page. Here, the variable uid holds ...

The component "SafeAreaViewRN" could not be located within the UIManager

Upon attempting to open a bundle on my Android device, I encountered the following error message: A warning was displayed stating that the app was accessing a hidden field in android's view accessibility delegate. Additionally, an Invariant Violati ...

The Ajax Process continues to run even after the user has navigated away from the page

Currently, I have a JavaScript function that refreshes a specific section of a Rails-generated view every 2.5 seconds using a JS request to update a basic progress bar. function refreshPage(){ $.ajax({ type:"GET", dataType:"script" }) } s ...

Tips for Uploading Large Images to Backend API in Next.js

As I work on building my portfolio using NextJS, I encountered an issue with the Project Functionality. When converting images to base64 and sending them to an API for uploading on Cloudinary, everything runs smoothly as long as the total size of the req ...

Effortlessly glide through entire pages using the mouse wheel for seamless scrolling

I provide a seamless full-page scrolling experience using the mouse wheel. However, the scrollIntoView function does not seem to function within the @HostListener('wheel', ['$event']). Here is a snippet from app.component.html file: & ...

Using ChartsJs to visualize input data formatted in the German data format

I am relatively new to working with Charts.js, but I will need it to generate some visually appealing graphs for my website. In the background, I have a Django project running that calculates a specific set of numbers for me. Due to the language setting in ...

"Troubleshooting alert: Encounter an error message saying 'process is not defined' when attempting to load the grpc package using proto-loader and grpc-js within a

Looking for help with integrating a typescript Vue.js component that needs to make a grpc call. The proto file can be found here: https://github.com/floydjones1/ts-node-grpc/blob/main/proto/random.proto Here is the component.vue code snippet: <script ...

Issues arise when upgrading from Angular 8 to 9, which can be attributed to IVY

After successfully upgrading my Angular 8 application to Angular 9, I encountered an error upon running the application. { "extends": "./tsconfig.json", "compilerOptions": { "outDir": ". ...

Dynamic manipulation of classes based on user attributes

One thing I've noticed is that certain WordPress themes, like 'Thematic', include user-specific classes in the body element to avoid using CSS browser hacks. For example: wordpress y2010 m02 d26 h05 home singular slug-home page pageid-94 pa ...

`Combining Promises and yields for seamless functionality`

I have been struggling to incorporate yield with a created Promise. Despite extensively researching, I am still unable to understand where I am going wrong in my implementation. Based on my understanding, when calling the generator function, I need to use ...

unable to integrate express auth middleware into system

I am having trouble with using the auth middleware in Express.js for role-based authentication. Even after passing the access token as a bearer token post login, authentication does not seem to work properly. This is the auth middleware code: const pass ...