Skip to content Skip to sidebar Skip to footer

Fastest Way To Find Object In Nested Array/object

I have the following array of objects who also have an array on one property: const boards = [ { id: 1, name: 'Lorem ipsum', tasks: [ { id: 42, ... }, { i

Solution 1:

Create a new lookup table of tasks and their associated index inside boards:

var taskIds = {
  12: 1,
  85: 1,
  14: 1,
  42: 0,
  65: 0,
  24: 0
};

From there, finding a task and associated board is only O(1) * 2

Example using Lodash:

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

Now you can easily find a board by task index in constant time:

boards[taskIds[65]]


Post a Comment for "Fastest Way To Find Object In Nested Array/object"