Quickest method to locate an item within a deeply nested array or object

I am presented with an array of objects, each containing a property that is also an array:

const boards = [
  {
    id: 1,
    name: 'Lorem ipsum',
    tasks: [
      { id: 42, ... },
      { id: 65, ... },
      { id: 24, ... },
    ],
  },
  {
    id: 2,
    name: 'Lorem ipsum',
    tasks: [
      { id: 12, ... },
      { id: 85, ... },
      { id: 14, ... },
    ],
  },
];

I am interested in finding the most optimal and efficient method to locate the index of a specific task (along with its corresponding board). While I have devised a solution, I am open to exploring alternative approaches that may offer improved performance, especially when handling larger datasets. As a note, the number of boards will generally be small (less than 10), but there could potentially be hundreds of tasks.

const idToFind = 1;

let boardIndex = null;
let taskIndex = null;

boards.some((board, index) => {
  taskIndex = board.tasks.findIndex(task => task.id === idToFind);

  // if the task is found, assign board index and terminate search
  if (taskIndex > -1) {
    boardIndex = index;
    return true;
  }

  return false;
});

Answer №1

Create a brand-new table for tasks and their corresponding indexes within the boards collection:

let taskIndexes = {
  12: 1,
  85: 1,
  14: 1,
  42: 0,
  65: 0,
  24: 0
};

With this lookup table in place, locating a task and its associated board is now achieved in constant time (O(1) * 2).

Check out an example using Lodash below:

let taskIndexes = {};
_.each(boards, function(board, index) {
  _.each(board.tasks, function(task) {
    taskIndexes[task.id] = index;
  });
});

You can now quickly retrieve a board by task index with simple one-step access:

boards[taskIndexes[65]]

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

Having trouble with a switch statement in Javascript that is unable to find a case for "none."

In my code, I am checking to see if there is a ball in a specific map point and then changing the color of the pixels where the ball is located to match the color of the ball. Here is my code snippet: function UpdateColorInMapPoints(mapPointIndexs) { / ...

What is the reason that selection disappears when right-clicking on highlighted text to bring up the context menu?

Currently, I am utilizing Material UI's context menu implementation in my project. On Chrome browser, everything is functioning flawlessly, as depicted below. Chrome: https://i.stack.imgur.com/i7eA1.gif However, I have encountered a peculiar issue ...

A guide on retrieving query string parameters from a URL

Ways to retrieve query string parameters from a URL Example Input - www.digital.com/?element=fire&solution=water Example Output - element = fire solution = water ...

Error: The image preview feature is malfunctioning in the Javascript code

Let me start by explaining the code. There are two views where I create a preview of an image from an input file. The first view contains a form for creating a project: <table> <tr> <td> <img src="" ...

How to Generate a JSON Cookie Array?

Currently, I am in the process of leveraging jquery's json to form a cookie array. The script I have managed to put together thus far is functional except for the part pertaining to the array. Would someone be able to guide me on how to construct an a ...

Exploring the features of AngularJS, including ngTranscluded, angular.noop, and the differences between Inter

I have some doubts about certain concepts in AngularJS such as- Reference (The official documentation is a bit confusing on these topics.) When should we use the "ngTranscluded" directive? Under what circumstances would we need to create a function that ...

Disqus API to enable real-time commenting on websites

I am currently working on a web application that allows users to create their own pages using various widgets, including the Disqus API. I am facing some challenges with implementing the Disqus API on the website. I have read the documentation at , but I a ...

The image fails to load after I moved the routers from the server file (entry point file) to the controller file

I recently made the decision to transition two routers from my server file to my controller file in order to adhere to the MVC format. However, after making this change, I realized that the logo image is no longer visible on those routers. It seems like al ...

`How can I retrieve environment variables in React or inject them into a React application?`

I attempted to include the following code in the plugins section of my webpack configuration, but it resulted in an unusable build. It's worth noting that I am not using create-react-app. new webpack.DefinePlugin({ 'process.env': dotenv. ...

Trackball's controls are not responding correctly

Recently, I have been using trackball controls and I've come across a strange bug. When I pan and then zoom out from my new position, the controls start to behave erratically, pulling towards the origin (the further I pan, the worse the issue becomes) ...

Issue with Promise function not resolving in the context of javascript and Wit.ai

Currently, I am in the process of updating the functions in my messenger/wit.ai chat bot to transition from using callbacks to promises. The initial format functions properly: ['buildScenario'](sessionId, context, cb) { var trendChoice = s ...

Implementing proper data return in MVC4 through an Ajax call

When using ajax to call an action in a controller, the code may result like this: $.ajax({ type: "POST", url: "getUserInfo.json", data: "", success: function (data) { if (data.resultInfo.resu ...

Using JavaScript, create a set of buttons within a div element and implement

$(document).ready(function() { $('#b1').click(function() { $('#uch').toggle("slow"); }); $('#b2').click(function() { $('#uch2').toggle("slow"); }) }) Although I'm not a program ...

Vue Subroutes within nested components do not automatically load

My application features a sidebar that I want to utilize to load the Patient view by default when accessing patient/:id. This should also trigger the loading of the PatientDashboard sub-view. Within the Patient view component, there is a router-view that ...

Creating dynamic HTML elements can be achieved by using JavaScript to dynamically generate and

I have an array var elements = ["What?", "How", "Who", ......]; My goal is to generate the following components: <html .. whatever> <div id="q1"> What? </div> <input type="text" id="a1"></input> <div id="q2"> How ...

Explore the Star Wars API using interactive buttons to navigate between different planetary pages

I've been working with the incredibly popular StarWars API and have successfully extracted data from the initial page of planets after some research. However, a new challenge has arisen. My task now is to implement buttons that allow users to navigat ...

Assigning values to a C array can still function even when exceeding the bounds

Can you explain why the code below seems to execute the printf() function before the variable i reaches 14? Shouldn't the execution fail once i exceeds the 10th element of the array? Even if I modify the loop as shown below: for(i=0; i<100; i++) ...

Three.js is struggling to load materials due to a property reading error (Attempting to access length of an undefined property)

As I dive deeper into learning three.js, I've encountered a stumbling block that has halted my progress. Despite spending days scouring for solutions, I have not been able to find a suitable answer to my dilemma. The issue pertains to the inability ...

Recursively generate a Java input array by implementing conditions using if/else statements

My homework assignment task involves... In a row, we have bunnies numbered 1, 2, ... n The even numbered bunnies (2, 4, ..) have 2 ears. The odd numbered bunnies (1, 3, ..) have 3 ears. To recursively calculate the total number of "ears" in the bunny li ...

Using jQuery to exclude elements with .not() and iterate through elements with .each() while

My task involves modifying the value of a span element that contains another nested span. I'm attempting to exclude the nested span's class within the .each() function. The current code adjusts the price by subtracting a specific percentage, but ...