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

What is the best way to end a Google OAuth session using Firebase on an Ionic 2 application?

My Ionic 2 app integrates Google Authentication using Firebase. I have implemented a logout button within the app that calls the Firebase unauth() method. However, this only disconnects the Firebase reference and does not terminate the Google OAuth session ...

Unable to modify the theme provider in Styled Components

Currently, I am attempting to customize the interface of the PancakeSwap exchange by forking it from GitHub. However, I have encountered difficulties in modifying not only the header nav panel but also around 80% of the other React TypeScript components. ...

I am unable to refresh the table data in Angular

Here is the code that I am currently working with: I am facing an issue where my webpage is not updating its data after performing delete or any other operations. The user list is not being displayed in the data. Despite my attempts, I have been unable to ...

The Azure function encounters an AuthorizationFailure error while attempting to retrieve a non-public file from Azure Blob Storage

Within my Azure function, I am attempting to retrieve a file from Blob Storage labeled myappbackendfiles. The initial code (utils/Azure/blobServiceClient.ts) that initializes the BlobServiceClient: import { BlobServiceClient } from "@azure/storage-bl ...

What is the process for modifying href generation in UI-Router for Angular 2?

I am currently working on implementing subdomain support for UI-Router. Consider the following routes with a custom attribute 'domain': { name: 'mainhome', url: '/', domain: 'example.com', component: 'MainSiteC ...

The issue arises when using Angular Material as it seems that passing a data object to a matdialog dialog

After reviewing multiple posts and carefully examining the process of passing data from an Angular Component to MatDialog, I am facing an issue where 'undefined' is being returned when the dialog loads. Below is the code snippet I have been work ...

Nestjs struggles with resolving dependencies

Having trouble finding the issue in my code. (I'm still new to nestjs and trying to learn by working on some apps). The console log is showing the following error: Nest can't resolve dependencies of the UrlsAfipService (?). Please ensure tha ...

The ng2-intl encounters an issue when trying to resolve symbol values statically

I'm struggling with a common issue and can't seem to find a solution that works. My setup involves Angular 4.2.6 along with ng2-intl 2.0.0-rc.3. Despite trying the following code, I am still facing issues: export function intlFactory(http:Http ...

Angular 7 and its scrolling div

Currently, I am working on implementing a straightforward drag and drop feature. When dragging an item, my goal is to scroll the containing div by a specified amount in either direction. To achieve this, I am utilizing Angular Material's CDK drag an ...

Using type definitions in non-TS files with VSCode: A beginner's guide

My code is not in TypeScript, shown here: // foo.js module.exports = app => { // some logic here } I want to enhance my development experience by using TypeScript definition files to specify the type of the argument app, enabling VSCode to provide ...

Retrieve data from an array of objects nested within another object

Imagine a scenario where there is an object containing an array of objects. let events = { "id": 241, "name": "Rock Party", "type": "party", "days": [ { "i ...

How to access JSON array data in PHP without using a loop to iterate through the keys

$c_array when printed displays the following data: Array ( [0] => Array ( [Category_Name] => sample quiz question 1 [Score] => 50 ) [1] => Array ( [Category_Name] => sample quiz question 2 [Score] => 100 ) ) <p>/<em>C ...

Seamlessly incorporating Storybook with Tailwind CSS, Create Next App, and TypeScript

*This is a new question regarding my struggles with integrating Storybook and Tailwind CSS. Despite following the recommended steps, I am unable to make Tailwind work within Storybook. Here's what I've done: I started a TypeScript project from s ...

Master the art of manipulating JSON arrays with jQuery

Looking to extract the information with a specific key and payment value from a JSON array generated by an API request. The desired data is: "Key":"PCP","Payment":170.08 The array in question looks like this: {"VehicleResults":[{"Id":"0","FinanceProduct ...

Mocking Firestore v9 getDocs() in Jest: A Comprehensive Guide

After upgrading our webapp from Firebase v8 to v9, we encountered various issues due to the new syntax. As I am still relatively new to Jest and Firebase/Firestore, not everything is completely clear to me yet ... I am attempting to mock getDocs from fire ...

Having trouble fixing TypeScript bugs in Visual Studio Code

I am encountering a similar issue as discussed in this solution: Unable to debug Typescript in VSCode Regrettably, the suggested solution does not seem to resolve my problem. Any assistance would be greatly appreciated. My directory structure looks like ...

The delay function in RxJS allows for waiting to return a value until a specific condition is met within a stream and

Currently, I am facing an issue with a method in my application that triggers a server request. This method has access to a stream from the redux-store and needs to execute a callback only when the result of the request is found in the mentioned stream. Th ...

Why does HttpClient in Angular 4 automatically assume that the request I am sending is in JSON format?

Currently, I am working with Angular 4's http client to communicate with a server that provides text data. To achieve this, I have implemented the following code snippet: this.http.get('assets/a.txt').map((res:Response) => res.text()).s ...

Typescript - using optional type predicates

I'm looking to create a custom type predicate function that can accurately determine if a number is real and tighten the type as well: function isRealNumber(input: number | undefined | null): input is number { return input !== undefined && ...

Inserting Array Type Values into Node.js and MongoDB

I need assistance with inserting array type values into the database. Currently, when I try to do so, it results in a blank array both in the database and when accessing req.body. Can someone please help me resolve this issue? Below is the method I am us ...