Efficient method for iterating through three arrays that have matching values and satisfy specified conditions in TypeScript

Struggling to speed up my Excel sheet creation time, currently taking over 20 seconds. I'm using the code below to compare three arrays and get the desired output:

for (let i = 0; i < this.arrayNumberOne[0].length; i++) {
    let orangeOne = this.arrayNumberOne[0][i]['item_1'];
    let orangeTwo = this.arrayNumberOne[0][i]['item_2'];
    let orangeThree = orangeOne.concat(orangeTwo)

    for (let k = 0; k < this.arrayNumberTwo[0].length; k++) {
        let appleOne = this.arrayNumberTwo[0][k]['item_1'];
        
        for (let j = 0; j < this.arrayNumberThree[0].length; j++) {
            let grapeOne = this.arrayNumberThree[0][j]['item_1'];
            let grapeTwo = this.arrayNumberThree[0][j]['item_2'];
            let grapeThree = this.arrayNumberThree[0][j]['item_3'];
        
            if (orangeThree == grapeOne && appleOne == grapeTwo) {

                if (grapeThree == null || grapeThree == '') {
                    // print to response to excel
                }

                else if (grapeThree == 'sells') {
                    //  print stuff to excel
                }

                else if (grapeThree == 'buys') {
                    // print stuff to excel
                }
            }
        }
    }
}

Considering hashmaps and interfaces but need help implementing them here. Open to suggestions on how to optimize the process.

Edit:

https://i.stack.imgur.com/9kuPn.png

Playground Link

Answer №1

What catches my attention is the presence of 3 nested loops in this code snippet, even though the data being processed is 2D. Typically, you would only expect 2 nested loops - one for X and one for Y. The crucial aspect to consider here is optimizing the process of retrieving the value of each cell to ensure efficiency, as this operation occurs frequently.

An effective strategy is to preprocess the values (representing actions) that populate the cells in such a way that facilitates quick lookups.

For instance:

// Index all actions based on player id and item name
const indexedActions: {
    [playerId: string]: {
        [itemCatName: string]: string
    }
} = {}

// Iterate through all actions to create an index.
for (const {playerId, itemCatName, action} of actions) {
    if (!indexedActions[playerId]) indexedActions[playerId] = {}
    indexedActions[playerId][itemCatName] = action
}

As a result of this processing, the data will be structured like:

{
    "12": {
        "potionsmall-potion": 'buy'
        // etc...
    }
    // etc...
}

This indexing significantly simplifies the lookup process for any cell:

indexedActions[playerId][itemName]

By doing so, the innermost loop can be eliminated entirely.

// Loop through items
for (let i = 0; i < items.length; i++) {
    let itemCat = items[i]['itemCategory']
    let itemNam = items[i]['itemName']
    let combineCat = itemCat.concat(itemNam)
    
    // Iterate through players
    for (let k = 0; k < players.length; k++) {
        let playerIdentify = players[k]['playerId']
        
        // Retrieve the action taken by this player regarding this item
        const actionToDo = indexedActions[playerIdentify][combineCat]

        // perform actions based on retrieved action
    }
}

Before Optimization

  • for every item
    • for every player
      • for every action
        • doLogic()

In this scenario, "doLogic" is executed

itemCount * playerCount * actionCount
times.

After Optimization

  • for every action
    • index each action
  • for every item
    • for every player
      • doLogic()

Though requiring additional upfront work, the optimization brings down the number of times doLogic is executed to itemCount * playerCount, resulting in a significant enhancement.

Moreover, the refactored code is more concise and easier to comprehend!

Explore playground

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

Can you tell me the data type of IconButtons in Material UI when using TypeScript?

Currently, I am in the process of creating a sidebar using Material UI in Next JS with typescript. My plan is to create a helper function that will help display items within the sidebar. // LeftSidebar.tsx import {List,ListItem,ListItemButton,ListItemIcon ...

Sending an Ajax request using an array of parameters and then accessing them in PHP

I have created a JavaScript function that facilitates AJAX posts by accepting an array of parameters. The function is outlined below: /** * A quick function to execute an AJAX call with POST method and retrieve data in JSON format * @param {string} url - ...

React with Typescript allows us to refine the callback type depending on the presence of an optional boolean prop

In my project, there's a component <Selector /> that can optionally accept a parameter called isMulti: boolean. It also requires another parameter called onSelected, whose signature needs to change depending on the value of isMulti (whether it i ...

Transforming substantial quantities of data into a string array in JavaScript

I have around 2000 items of data that I work with on a regular basis in Visual Studio Code. Is there a way to convert this data into a string array without having to manually add quotes around each item using JavaScript? var array = [ a2kjda a2dkj ...

What is the best way to retrieve the value from a Material UI textfield after hitting the enter key

Having trouble retrieving input values with the provided code. Attempted using onKeyUp, onKeyDown, and onKeyPress, but none of them returned the value as desired. Typically, I would use the onChange property to get the value, but it triggers for every ne ...

Using TypeScript, Material UI introduces a new property to the primary object on the palette

Experimenting with the customization of MUI v5 theme has been a fun challenge in my current project. I have successfully tailored the theme to suit my requirements so far, but now I am faced with the task of adding a new property to the primary object defi ...

The Network plugin is having issues with the PWA application in Ionic 4

I've been utilizing the network plugin successfully on native/Cordova devices. However, I have encountered an issue when trying to use it on a PWA app (specifically when there is no wifi connection). Can anyone shed light on why this might be happenin ...

Issue with Angular 6 where data is not binding to the UI on initialization

I am struggling with binding dynamic data to the UI and Data tables on my website. Despite trying various methods, I have not been able to achieve success. Currently, I am using the smart admin latest theme for development. When I make a call to the API, ...

Errors caused by Typescript transpilation only manifest on the production server

During the process of updating my node version and dependencies on both machines, I came across an issue where building my app in production on one machine resulted in an error, while building it on my main machine did not. I found that the errors disappe ...

Is it possible to organize multiple tables within a single JSON structure without relying on JArray?

I am currently developing a program similar to IMDB, where I am showcasing individuals with a filmography, discography, and more. After setting up my view in MVVM, I am now working on serializing my JSON data to align with it. At the moment, I am consolida ...

Converting data received from the server into a typescript type within an Angular Service

Received an array of Event type from the server. public int Id { get; set; } public string Name { get; set; } public DateTime Start { get; set; } public DateTime End { get; set; } For Angular and TypeScript, I need to transform it into the following clas ...

Utilizing a personalized (branched) @types package

I have taken the @types/stripe package from the DefinitelyTyped repository on GitHub and created my own version in my personal GitHub repo / npm module. I understand that this custom type module may not work automatically. I attempted to integrate it by ...

Angular 7 - Implementing periodic JSON data retrieval from server and maintaining local storage within Angular application

Seeking guidance on how to handle updating a static json file stored in the assets directory in an Angular 7 project. The goal is to periodically fetch a json from a server, check for updates, and perform post-processing on the data in the static file (ess ...

Designing php/mysql data in a container

After successfully converting an ordered list output into a div output, I now face the challenge of stacking arrays on top of each other (and side by side with the two divs) like they would in an ordered list. Here is the original code snippet: <?php ...

Error message encountered in Typescript eslint: File extension "ts" is missing in import statement for the specified file

I am encountering an issue with my Node/Express application created using Typescript. The problem lies in eslint throwing an error that says: Missing file extension "ts" for "./lib/env" import/extensions Below is the content of my .eslintrc file: { ...

Develop a PHP master-detail page for enhanced user experience

Is it possible to create a master-detail page using PHP where the data is sourced from an associative array instead of a MYSQL database? I plan to retrieve the data from a mysql database table and store it in an associative array for manipulation. My goal ...

The function useNuxtApp() in Nuxt 3 is returning an unknown type

I have been working on creating a helper that can be used across all composables and applications in my Nuxt plugin. Here is how the code looks: // hello.ts export default defineNuxtPlugin(async nuxtApp => { nuxtApp.vueApp.provide('hello', ...

Angular 8 delivers an observable as a result following a series of asynchronous requests

I am working on a simple function that executes 3 asynchronous functions in sequence: fetchData() { this.fetchUsers('2') .pipe( flatMap((data: any) => { return this.fetchPosts(data.id); }), fl ...

Eliminate redundant arrays across several JSON files with Python

I have a collection of JSON data records such as { "Stat": "DEN", "Change": [{ "From": "", "To": "DEN", "changeTimestamp": "202 ...

What is the best way to include multiple targets/executables within a single Node.js repository?

My React Native app is developed using TypeScript, and I want to create CLI tools for developers and 'back office' staff also in TypeScript. These tools should be part of the same monorepo. After attempting to do this by creating a subfolder wit ...