Improprove the performance of an array of objects using JavaScript

Hello there, I am currently in the process of creating an array.

this.data = [{
  label: 'Total',
  count: details.request.length,
}, {
  label: 'In-Progress',
  count: details.request.filter((obj) =>
    obj.statusId === 0 ||
    obj.statusId === 1 ||
    obj.statusId === 3 ||
    obj.statusId === 4
      ? obj
      : null,
  ).length,
}, {
  label: 'Success',
  count: details.request.filter(({ statusId }) =>
    statusId === 6 ? statusId : null,
  ).length,
  additionalObj: details.request.filter((obj) =>
    obj.statusId === 6 ? obj : null,
  ),
}, {
  label: 'Failed',
  count: details.request.filter(({ statusId }) =>
    statusId === 2 || statusId === 5 ? statusId : null,
  ).length,
  additionalObj: details.request.filter((obj) =>
    obj.statusId === 2 || obj.statusId === 5 ? obj : null,
  ),
}];

I have structured the array as required but I believe there is room for optimization. I find myself using the array filter method multiple times to calculate both the count and additionalObj properties. I am open to suggestions on how I can use the filter method more efficiently for both calculations. Any assistance would be greatly appreciated.

Just so you know, this is what the details structure looks like:

details = {
  request: []
}

Answer №1

What is the specific rationale behind your choice of using filter rather than a for loop?

You could alternatively implement the code in the following manner, utilizing only a single loop:

function categorizeData(details: { request: { statusId: number }[] }) {
    let inProgressCount = 0;
    
    let successCount = 0;
    const successAdditionalObj: { statusId: number }[] = [];
    
    let failedCount = 0;
    const failedAdditionalObj: { statusId: number }[] = [];
    
    details.request.forEach((req) => {
        switch (req.statusId) {
            case 0:
            case 1:
            case 3:
            case 4:
                inProgressCount += 1;
                break;
                
            case 6:
                successCount += 1;
                successAdditionalObj.push(req);
                break;
                
            case 2:
            case 5:
                failedCount += 1;
                failedAdditionalObj.push(req);
                break;
                
            default:
                break;
        }
    });
    
    return [
        {
            label: "Total",
            count: details.request.length || 0,
        },
        {
            label: "In-Progress",
            count: inProgressCount,
        },
        {
            label: "Success",
            count: successCount,
            additionalObj: successAdditionalObj,
        },
        {
            label: "Failed",
            count: failedCount,
            additionalObj: failedAdditionalObj,
        },
    ];
}

this.resultData = categorizeData(dataToTransform);

Answer №2

Your inquiry lacks quality, as does your code. However, I will address the shortcomings in your code and provide solutions for improvement.

A major performance flaw in your code is the repeated iteration of details.request when filtering can be done just once.

To avoid iterating multiple times for different filters, consider using reduce to streamline the process.

You can achieve this by utilizing reduce on details.request to create an object with status properties instead of storing them separately:

this.data = details.request.reduce(
  (previous, currentRequest) => {
    switch (currentRequest.statusId) {
      case 2: // failed
      case 5: // failed
        previous.Failed.push(currentRequest);
        return previous;
      case 6: // success
        previous.Success.push(currentRequest);
        return previous;
      default:
        previous.InProgress++;
        return previous;
    }
  },
  { Total: details.request.length, InProgress: 0, Success: [], Failed: [] }
);
// this.data.Total: number
// this.data.InProgess: number
// this.data.Failed: requestItem[]
// this.data.Success: requestItem[]

If you require data in a specific format for an API, here's how you can structure it based on your approach:


this.data = details.request.reduce(
  (previous, currentRequest) => {
    switch (currentRequest.statusId) {
      case 2: // failed
      case 5: // failed
        previous[3].count++;
        previous[3].additionalObj.push(currentRequest);
        return previous;
      case 6: // success
         previous[2].count++;
         previous[2].additionalObj.push(currentRequest);
        return previous;
      default:
        previous[1].count++;
        return previous;
    }
  },
  [
    {
      label: "Total",
      count: details.request.length,
    },
    {
      label: "In-Progress",
      count: 0,
    },
    {
      label: "Success",
      count: 0,
      additionalObj: [],
    },
    {
      label: "Failed",
      count: 0,
      additionalObj: [],
    },
  ]
);
// this.data: [{label:string, count:number},
//   {label:string, count:number},
//   {label:string, count:number,additionalObj:requestItem[]},
//   {label:string, count:number,additionalObj:requestItem[]}]

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

Analyzing all the <option> elements within a <select> tag with jQuery

I have a WordPress plugin in development and I am currently facing an issue with comparing user-input from an <input> element to a set of <option> elements within a <select> element. Here is my current approach: $('button#test_bu ...

Caution: Additional server attributes detected: style

Alert in my Next.js project, I encountered the following message: Notice: Server is sending additional attributes: style I am uncertain about the source of this warning and therefore unable to provide any code snippet. ...

The product has been taken out of the cart, yet it has not been reinserted into the cart

The product disappears from the cart after clicking on Add to Cart, but it doesn't reappear when clicked again. //function for adding only one item to cart document.getElementById('btn1').onclick = function() { addItemToCart() }; fun ...

Angular 2 - Dragula for ng2

<div *ngFor="let col of columns"> ... <div [dragula]="'tickets-list'" [dragulaModel]="col.tickets" (drop)="onDrop($event, col)"> <ul> <li *ngFor="let ticket of col.tickets"> {{ ticket }} </li ...

Is there a way to validate form input before inserting it into a database using the onsubmit event?

Looking for a way to enhance the verification process of my signup form, I aim to ensure that all data entered is validated before being saved in the database. The validation process involves checking if the phone number consists only of numerical values a ...

After updating the TypeScriptOutDir configuration, breakpoints are not being reached

Currently, I am utilizing Visual Studio Professional 2013 Update 3 and have developed a Node console Application with the simple "hello world" log instruction. Setting a breakpoint in this instruction and running the debugger functions smoothly, hitting th ...

What is the best way to implement an onClick event listener in a TypeScript React application?

Is there a way to properly add an onClick event listener to a div element in my code snippet below? useEffect(() => { if (ref.current === null) { return; } const handleClick = (el: HTMLDivElement, e: MouseEvent) = ...

Is it possible for me to overlap a text over hidden text, and if the hidden text becomes visible through JavaScript, my text will shift to the right of the now visible hidden text?

I'm currently working on a website for a company that requires users to complete all the information before proceeding. To achieve this, I created a form with the following code: <form action="Owners Infoback.php" onsubmit="return validateFo ...

JQuery grid pagination bar mysteriously missing

I'm having an issue with a Jquery grid that is built on an HTML table. I've properly configured the grid properties, including implementing pager functionality with a page size of 10. However, I am unable to see the page up and page down buttons ...

What steps should I take to adjust the price when multiple items are chosen?

I am working on a school project that requires JavaScript programming assistance. You can view the code here: https://jsfiddle.net/zvov1jpr/3/ HTML: <script src="java.js"></script> <div id="formular"> <div id=&qu ...

jQuery unable to target Bootstrap button

I've been experiencing some trouble trying to attach a listener to a button I made with Bootstrap. <button type="button" id="buttonone" class="btn btn-default btn-lg good"> <span class="glyphicon glyphicon-minus" aria-hidden="true">< ...

Tips for returning JSON data using AJAX

When working with native JS, I am familiar with using AJAX to display the output from PHP/mySql that is not Json Encoded in the element "some_id" like this: <script> function addItem(value) { xmlhttp = new XMLHttpRequest(); xmlhttp.onrea ...

Missing Directory Issue Upon Deploying Node.js App on Google App Engine

I have a Node.js web application built using TypeScript and Koa.js that I am looking to deploy on Google App Engine. The code has already been transpiled into JavaScript and is stored locally in the ./dist/src/ directory. Essentially, I only need to depl ...

Issue with NodeJS Express's reverse proxy due to an invalid TLS certificate alternative name

I have configured a reverse proxy on my endpoint as shown below: var express = require('express'); var app = express(); var httpProxy = require('http-proxy'); var apiProxy = httpProxy.createProxyServer(); var serverOne = 'https://i ...

My attempts to utilize the local storage key have been unsuccessful in storing my todo list. I am uncertain where the issue lies within my code

I've been working on a Todo List with local storage in React, but I'm running into an issue. It seems that my todos aren't getting stored properly and are disappearing every time the page refreshes. I need to figure out what's causing t ...

Discover a method to receive an alert when the mouse exits the inner window along the y-axis

Is there a way to receive an alert if the mouse moves out of the inner window solely in the y-axis? Currently, alerts are triggered when the mouse moves out on both x-axis and y-axis. For example, if the mouse pointer hovers over the address bar coming fro ...

Dealing with Undefined TypeScript Variables within an array.forEach() loop

Could someone help me understand my issue? I have an array of a specific object, and I am trying to create a new array with just the values from a particular field in each object. I attempted to use the forEach() method on the array, but I keep encounteri ...

Encountered a module build failure due to the inability to resolve the 'bootstrap-sass' module, a required installation when configuring bootstrap version v3

Encountered an error while building an angular project: ERROR in ./~/bootstrap-loader/lib/bootstrap.loader.js!./~/bootstrap-loader/no-op.js Module build failed: Error: Could not resolve module 'bootstrap-sass' which must be installed when bootstr ...

JavaScript: How to Build a Digital Grocery List with Browser Storage

Struggling with a tough exercise question, I could use some help deciphering it. https://i.stack.imgur.com/V5he2.png Here is how I've started the code: <!DOCTYPE html> <html> <head> <title></title> <script> fun ...

determine the color of the pixel at the top left corner of a jpg image

If we were given a specific URL, for instance, "//upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg", how can we use javascript (specifically jQuery or Angular) to obtain the top left coordinates (or any (x,y) coordinates) of this image? Just to clarify, ...