Splitting an array of objects into multiple arrays of objects based on their properties

At the moment, I am working with an array that contains multiple objects

const bankData = [
    {
      "bank": "Chase",
      "monthEndBalance": "72,175.88",
      "bankStatementDate": "2020/10/31"
    },
    {
      "bank": "Chase",
      "monthEndBalance": "93,412.79",
      "bankStatementDate": "2020/07/31"
    },
    {
      "bank": "Chase",
      "monthEndBalance": "88,175.88",
      "bankStatementDate": "2020/11/30"
    },
    {
      "bank": "Chase",
      "monthEndBalance": "102,200.12",
      "bankStatementDate": "2020/12/31"
    },
    {
      "bank": "Goldman Sachs",
      "monthEndBalance": "72,276.12",
      "bankStatementDate": "2020/11/30"
    },
    {
      "bank": "Goldman Sachs",
      "monthEndBalance": "52,276.12",
      "bankStatementDate": "2020/10/31"
    },
    {
      "bank": "Goldman Sachs",
      "monthEndBalance": "102,276.12",
      "bankStatementDate": "2020/12/31"
    },
    {
      "bank": "Wells Fargo",
      "monthEndBalance": "33,276.12",
      "bankStatementDate": "2020/11/30"
    },
    {
      "bank": "Wells Fargo",
      "monthEndBalance": "12,276.12",
      "bankStatementDate": "2020/10/31"
    },
    {
      "bank": "Wells Fargo",
      "monthEndBalance": "150,276.12",
      "bankStatementDate": "2020/12/31"
    }
]

I am aiming to separate each bank into its own individual array of objects.

For example:


const bankOne = [
    {
      "bank": "Chase",
      "monthEndBalance": "72,175.88",
      "bankStatementDate": "2020/10/31"
    },
    {
      "bank": "Chase",
      "monthEndBalance": "93,412.79",
      "bankStatementDate": "2020/07/31"
    },
    {
      "bank": "Chase",
      "monthEndBalance": "88,175.88",
      "bankStatementDate": "2020/11/30"
    },
    {
      "bank": "Chase",
      "monthEndBalance": "102,200.12",
      "bankStatementDate": "2020/12/31"
    }
]

Although my current solution utilizes Array.filter, it is not scalable and would require modification for every new bank added. What would be the most efficient method to filter each bank into its own unique array of objects?

const chaseBank = bankData.filter(el => el.bank === "Chase")
const goldManBank = bankData.filter(el => el.bank === "Goldman Sachs")
const wellsFargoBank = bankData.filter(el => el.bank === "Wells Fargo")

Answer №1

One way to group objects is by using an object as a grouping mechanism.

const
    data = [{ bank: "Chase", monthEndBalance: "72,175.88", bankStatementDate: "2020/10/31" }, { bank: "Chase", monthEndBalance: "93,412.79", bankStatementDate: "2020/07/31" }, { bank: "Chase", monthEndBalance: "88,175.88", bankStatementDate: "2020/11/30" }, { bank: "Chase", monthEndBalance: "102,200.12", bankStatementDate: "2020/12/31" }, { bank: "Goldman Sachs", monthEndBalance: "72,276.12", bankStatementDate: "2020/11/30" }, { bank: "Goldman Sachs", monthEndBalance: "52,276.12", bankStatementDate: "2020/10/31" }, { bank: "Goldman Sachs", monthEndBalance: "102,276.12", bankStatementDate: "2020/12/31" }, { bank: "Wells Fargo", monthEndBalance: "33,276.12", bankStatementDate: "2020/11/30" }, { bank: "Wells Fargo", monthEndBalance: "12,276.12", bankStatementDate: "2020/10/31" }, { bank: "Wells Fargo", monthEndBalance: "150,276.12", bankStatementDate: "2020/12/31" }],
    result = data.reduce((r, o) => {
        (r[o.bank] ??= []).push(o);
        return r;
    }, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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 error message "TypeError: The object prototype can only be an Object or null: undefined in Angular"

When trying to launch my web app using 'ng serve', I am encountering an error that I cannot seem to resolve. The error message is quite cryptic, and despite updating dependencies and searching through similar questions, I am still unable to pinpo ...

How can we transfer a jQuery value from an input field without using a single

This task may seem challenging. How can single quotes be eliminated from a variable when passed directly to another variable? I am using jQuery variable $("#test").val() to extract the value from an input below <input type="text" ...

What steps are needed to enable autocomplete for input fields in React Native Elements on iOS?

I'm currently working on fine-tuning the autocomplete suggestions for my registration form. Within the react native elements input, I've already implemented fields for username, email, and password. Specifically for the email field, I have config ...

Creating a generic array type in TypeScript that includes objects with every key of a specified interface

I am working with an interface called Item interface Item { location: string; description: string; } Additionally, I have a generic Field interface interface Field<T extends object> { name: keyof T; label: string; } I want to create an Arra ...

Executing TypeORM commands yields no output

It's been a while since I last tested my Nest project with TypeORM, and now when I try to run any TypeORM command, nothing happens. I attempted to run TypeORM using these two commands: ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js ...

What are the steps to create a distorted effect on HTML using webGL?

Recently, I was experimenting with an interesting example from this link: . In my local environment, I tweaked the Three.js renderer to become an overlay by adjusting the z-index to 999 and setting {alpha: true} to make it transparent. Then, underneath th ...

How to conditionally apply a directive to the same tag in Angular 4

I am implementing angular 4 and have a directive in my template for validation purposes. However, I would like to first check if a specific condition is true before applying the directive. Currently, my code looks like this: <div *ngIf="groupCheck; els ...

The specified file cannot be found within the Node file system

I am working on a project that involves reading a file using Node fs, and I have the following code: const files: FileSystemTree = { "Component.tsx": { file: { contents: fs.readFileSync( `../../apps/components ...

Obtaining the server reference in deployd (Node.js) is a straightforward process that involves accessing

I am currently working with deployd and I require access to the current server object within a background thread. This particular situation does not involve any requests, responses, or sessions. Is there a method available to obtain this reference? ...

What is the significance of $() in jQuery?

I understand that $() is a selector, but I find it puzzling as to what it actually selects since there is nothing inside the parentheses. Is this a common practice or frowned upon in coding conventions? An example of where I have seen it used is when maki ...

Is there a way to filter out only the data for the month of August from a particular

$arr = [ (Object)[ 'interval' => "2018-08-26", 'product_id' => 12 , 'size' => 10 ], (Object)[ 'interval' => "2018-09-26", 'pr ...

Tips for confining the draggable div within its container

I've been working with React and TypeScript, and I recently added the W3School drag div example to my React app. However, I'm facing an issue where the draggable div is moving outside of the container. Can someone please guide me on how to confin ...

Using JavaScript and HTML to show the current month, date, and year on a webpage

I am looking to display not only the time, but also the month, date and year. My attempted solution involved creating variables for the month, day and year, and then using getElementById. Here is an example of what I tried: var d = date.getDay(); var mn ...

Is there a way to reposition the dynamically added URL path before the variables instead of after?

Just a brief introduction: In my Symfony-based ecommerce template, I have implemented a feature where all products from different pages are loaded using AJAX requests with an infinite scroll functionality. It works flawlessly when the URL is clear, like t ...

Utilize a method in Vue.js to filter an array within a computed property

I have a question regarding my computed property setup. I want to filter the list of courses displayed when a user clicks a button that triggers the courseFilters() method, showing only non-archived courses. Below is my current computed property implement ...

Attempting to initialize objects of varying sizes is not permitted

I am encountering a strange issue where the code generates numerous errors, but miraculously works when InputM[3][3] is set to 'blah'. Any idea why this could be happening? Here's the snippet of code in question: int n = 3; printf("%ld&bso ...

What is the method to adjust the colors of the Y-Axis for values that are either above or below zero in Chart.js 2.6?

Is there a way to dynamically change the colors of bars in a chart created using chart.js 2.6 based on whether the values are above or below zero? The data for the graph series is currently generated randomly but will eventually come from a database query. ...

Updating state in Redux from a different componentorModifying state

I'm currently learning about redux and I'm facing an issue with accessing the stored state (id) in my components. Specifically, I have a Footer component with a button that is supposed to modify the state in the Layout component. However, I am un ...

What is the best way to retrieve information from a json file using axios in a React project?

I'm having trouble retrieving JSON data. { ID string `json:"id"` Amount int `json:"amount"` Month string `json:"month"` PayFailed bool `json:"pay_failed"` } I’ve written the foll ...

Error: Failed to decode audio content due to a DOMException that was caught in the promise

Encountering an issue with the decodeAudioData method while utilizing the Web Audio API for playback in Chrome (works seamlessly in Firefox)- Sending the audio buffer, which has been recorded by the media recorder, back from the server. Server-side wss ...