What is the optimal method for iterating through a nested array?

I've been searching like this for quite some time now, and it seems there must be a more efficient approach. The scenario is that I have a double elimination tournament bracket and need to locate a specific game. The brackets for winners and losers are kept in an array with individual games stored within each of those arrays.

The format resembles the following:

{
   tournament: {
       brackets: [

           {games: [{id:'x'},{id:'y'},...,{id:'z'}]},
           {games: [{id:'x'},{id:'y'},...,{id:'z'}]}
           ]
       ]
   }
}

Below is the code snippet I am currently using to identify an ID.

for (var i = 0; i < tournament.brackets.length; i++) {
 for (var y = 0; y < tournament.brackets[i].games;length; y++) {
    // Check if the ID matches the known ID    
 }
}

Answer №1

If you've labeled the question as ES6, then there is a more efficient method to achieve this:

for (let bracket of tournament.brackets) {
  for (let game of bracket.games) {
    // Check if the object's ID matches a known ID
  }
}

Answer №2

If you find yourself frequently searching, one handy solution is to create a reverse lookup array based on the game id. Here's an example:

var gameLookup = {};
for (var index = 0; index < tournament.brackets.length; index++) {
 for (var num = 0; num < tournament.brackets[index].games.length; num++) {
    gameLookup[tournament.brackets[index].games[num].id] = { bracketIndex: index, gameIndex: num };
 }
}

Then when needed,

function locateGame( gameId, gameLookup, tournamentData ) {
    if ( !gameLookup.hasOwnProperty( gameId ) )
        return false;

    var coordinates = gameLookup[gameId];
    return tournamentData.brackets[coordinates.bracketIndex].games[coordinates.gameIndex];
}

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

Prop in a React component is undergoing mutation

I encountered a strange situation where a prop in a React component is being changed. Although it's technically not a mutation since it's an array in JavaScript, it should not be modified. To replicate the issue, I created a simple example: htt ...

Creating custom elements for the header bar in Ionic can easily be accomplished by adding your own unique design elements to the header bar or

I'm a beginner with Ionic and I'm looking to customize the items on the header bar. It appears that the header bar is created by the framework within the ion-nav-bar element. <ion-nav-bar class="bar-positive"> <ion-nav-back-button> ...

Using update_user_meta() to delete a post - A step-by-step guide

I have a list of articles loaded as IDs within an input value: $idThisPost = "19999"; <input id="input_post_id" type="hidden" name="varPostId" value="<?php echo $idThisPost; ?>"> Each article includes a remove button: <form id="saveId" ac ...

Tips for optimizing the efficiency of an iterative process on both a 2D and 1D NumPy array using vectorization in Python

To optimize my code and fully utilize NumPy's vectorization capabilities, I have successfully vectorized most computations in my code using `clr/vlr` functions. This is believed to be the best approach for NumPy, as further optimization with `np.einsu ...

What is the process for encrypting and decrypting image files over the internet?

I'm currently developing a web application that requires loading images into a canvas object, followed by extensive manipulation. My goal is to conceal the original source image file (a jpeg) in such a way that users on the client side cannot access i ...

Determining Visibility in Three.js: A Guide to Checking if an Object is in View of the Camera

Struggling to determine the best method for checking if an Object3d is visible to the camera. Imagine a sphere in the center of the screen with cubes randomly placed on its surface. I need a way to identify which cubes are visible (on the front half of th ...

Struggling to find your way around the header on my website? Let me give

I'm looking to display certain links prominently at the top of a page, similar to this example: "home > page1 > link1 > article 1." Can someone advise on how to achieve this using HTML, PHP, or jQuery? ...

What steps should be followed to upgrade node.js from version 5.9.1 to 6.14.0 in a secure manner

Our current node version is 5.9.1 and we are looking to transition to a newer version that supports ES6. Specifically, I am aiming to upgrade to at least version 6.14.0, which is known to support almost all of the ES6 features. However, I must admit that ...

Angular's lazy evaluation technique for single-shot binding on expressions

Since AngularJS version 1.3.0-beta.10, a new feature has been introduced called the "lazy one-time binding". To implement this feature, you can prefix simple expressions with ::, which instructs AngularJS to stop watching the expression after it has been ...

Encountered an Angular SSR error stating "ReferenceError: Swiper is not defined"

When attempting to implement SSR (Server-Side Rendering) in a new project, everything runs smoothly and without issue. However, encountering an error arises when trying to integrate SSR into an existing project. https://i.sstatic.net/QOI6A.png ...

Issue encountered while incorporating a PHP file into Javascript code

I'm facing a particular issue where I have a PHP file that is supposed to provide me with a JSON object for display in my HTML file. Everything seems to be working fine as I am receiving an output that resembles a JSON object. Here's the PHP file ...

There was a failure to retrieve any data when trying to send an ajax request to

When attempting to send JSON data to my PHP, I am not receiving any response when accessing it in my PHP code. Below is the Ajax request being made: var project = {project:"A"}; var dataPost = JSON.stringify(project); $.ajax({ url: 'fetchDate.p ...

Embed PHP script within the PrettyPhoto.js file

Looking to integrate a piece of PHP code into the prettyPhoto.js file. This is the snippet I'm currently working with. The section where I need to insert the PHP code is marked as ((CODE ME HERE)). (function($) { $.prettyPhoto = {version: ' ...

What is the best way to change the size of a QR code

My current HTML code: <input id="text" type="text"/> <div id="qrcode"></div> Previous version of JAVASCRIPT code: var qrcode = new QRCode("qrcode"); $("#text").on("keyup", function () { qrcode.makeCode($(this).val()); }).keyup().focus ...

Discovering the presence of a component in Angular 1.5

Link to embedded content $injector.has('myMessageDirective') is returning true, while $injector.has('myMessageComponent') is not. Has anyone else encountered this issue or found a solution? I am concerned that my components may not be ...

Can Angular 4 experience race conditions?

Here is a snippet of my Angular 4 Service code: @Injectable() export class MyService { private myArray: string[] = []; constructor() { } private calculate(result): void { myArray.length = 0; // Perform calculations and add results to myAr ...

The object's type remains a mystery

While working on implementing jwt authentication in Ionic, React with TypeScript, I faced a typescript error when trying to add a check in my App.tsx file after successful implementation. The error stated: Object is of type 'unknown' Below is ...

What is the best way to trigger a new css animation on an element that is already in the midst of

Let's talk about an element that already has an animation set to trigger at a specific time: .element { width: 100%; height: 87.5%; background: #DDD; position: absolute; top: 12.5%; left: 0%; -webkit-animation: load 0.5s ease-out 5s bac ...

Showing particular PHP array retrieved from MySQL

Currently, all columns from the MySQL result are being converted to JSON and displayed on the screen. However, I am interested in only printing two specific columns - $row['name'] and $row['gender']. Any suggestions on how to achieve th ...

Gallery of images resembling Getty Images without the use of a database

I want to put together an image display, similar to the functionality on Getty Images where clicking on an image brings up more details. Here is an example link from Getty Images: The image I am working with can be found here: All I need is a way to nav ...