Exploring the depths of nested object arrays and navigating through historical indexes

I am working with nested object arrays within an array and looking to determine the path of a specific key.

For instance:

const dataList = [
  [
      [{id: 100,name: 'Test1'}, {id: 120,'Test12'}],
      [{id: 101,name: 'Test1'}, {id: 121,'Test12'}],
      [{id: 102,name: 'Test1'}, {id: 122,'Test12'}],
    [
      [{id: 103,name: 'Test1'}, {id: 123,'Test12'}],
      [{id: 104,name: 'Test1'}, {id: 124,'Test12'}],
      [{id: 105,name: 'Test1'}, {id: 125,'Test12'}],
    ]
  ],
  [{id: 2,name: 'Test2'}, {id: 13,'Test13'}],
  [{id: 3,name: 'Test3'}, {id: 14,'Test14'}],
  [{id: 4,name: 'Test4'}, {id: 15,'Test15'}],
  [{id: 5,name: 'Test5'}, {id: 16,'Test16'}],
  [{id: 6,name: 'Test6'}, {id: 17,'Test17'}],
  [{id: 7,name: 'Test7'}, {id: 18,'Test18'}],
  [{id: 8,name: 'Test8'}, {id: 19,'Test19'}],
];

function findIndexPath(list, targetId) {
  //....
}

findIndexPath(dataList, 104); //result should be [0,3,1,0]
findIndexPath(dataList, 16); //result should be [4,1]

The arrays may have multiple levels of nesting.

Answer №1

Here is one possible solution:

const dataList = [
  [
    [ { id: 100, name: 'Test1' }, { id: 120, name:'Test12' } ],
    [ { id: 101, name: 'Test1' }, { id: 121, name:'Test12' } ],
    [ { id: 102, name: 'Test1' }, { id: 122, name:'Test12' } ],
    [
      [ { id: 103, name: 'Test1'}, { id: 123, name:'Test12' } ],
      [ { id: 104, name: 'Test1'}, { id: 124, name:'Test12' } ],
      [ { id: 105, name: 'Test1'}, { id: 125, name:'Test12' } ],
    ]
  ],
  [ { id: 2, name: 'Test2'}, { id: 13, name:'Test13' } ],
  [ { id: 3, name: 'Test3'}, { id: 14, name:'Test14' } ],
  [ { id: 4, name: 'Test4'}, { id: 15, name:'Test15' } ],
  [ { id: 5, name: 'Test5'}, { id: 16, name:'Test16' } ],
  [ { id: 6, name: 'Test6'}, { id: 17, name:'Test17' } ],
  [ { id: 7, name: 'Test7'}, { id: 18, name:'Test18' } ],
  [ { id: 8, name: 'Test8'}, { id: 19, name:'Test19' } ],
];

function findIndexPathRecursively(list, targetId, path) {    
    let result = -1;
    for (let i = 0; i < list.length; i++) {
        if (list[i] instanceof Array) {
            const index = findIndexPathRecursively(list[i], targetId, path);
            if (index !== -1) {
                path.push(i);
                result = index;
                break;
            }
        }
        else if (list[i].id === targetId) {
            path.push(i)
            result = i;
            break;
        }
    }
    return result;
}

function findIndexPath(list, targetId) {
    const path = [];
    findIndexPathRecursively(list, targetId, path);
    return path.reverse();
}

console.log(findIndexPath(dataList, 104)); // output  [0,3,1,0]
console.log(findIndexPath(dataList, 16));  // output: [4,1]

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

Remove elements generated by the .after method with Jquery

In my HTML file, I have a table with hard-coded column headers: <table id="debugger-table"> <tr> <th>Attribute</th> <th>Computed</th> <th>Correct</th> </tr> </table&g ...

Lack of animation on the button

Having trouble with this issue for 48 hours straight. Every time I attempt to click a button in the top bar, there is no animation. The intended behavior is for the width to increase and the left border color to change to green, but that's not what&ap ...

jQuery is in a constant state of indecision when it comes to determining the best way to manage buttons

A straightforward scenario. When a checkbox is checked, it activates a disabled button. Unchecking the box disables the button again. Sample Code: jQuery -> $('#subscribe_button').attr('disabled','disabled') $("[name= ...

Development is hindered due to Cors policy restricting access to the localhost webapp

Currently, I am working on developing a web application and an API simultaneously, but I'm facing some issues with CORS blocking. This concept is relatively new to me, and I'm eager to improve my understanding. Firstly, I have set up an Express ...

What would be the most efficient method in Angular for saving and retrieving information on whether a user has previously selected a checkbox?

I am currently in the process of learning angular as I develop a web application that resembles a todo list, specifically focused on football teams. In this application, users can navigate through a menu to select a league from four options. The applicatio ...

What is the best way to reset Owl Carousel following an ajax request?

I am attempting to reinitialize the owl carousel following a successful ajax call. The ajax call will update the data while retaining the same view. I am encountering an issue where the carousel structure in the view does not reinitialize, and I am unsure ...

Easy steps to dynamically add buttons to a div

I need help with a JavaScript problem. I have an array of text that generates buttons and I want to add these generated buttons to a specific div element instead of the body. <script> //let list = ["A","B","C"]; let list = JSON.p ...

Whenever I find myself being redirected to the login page, my goal is to eliminate the bottomTab from view

I'm looking to eliminate the bottom tab when I land on the login page, even though I've set it up for all pages. However, whenever I click on the login button, the tab remains visible. Here is my current code: import React, { useContext } from & ...

Only make an AJAX request for suggestions with jQuery Autocomplete if the item does not match any data from the previous request

I am currently working with jQuery Autocomplete functionality. The issue I am facing is that it triggers an AJAX request every time a key is pressed, which is not desirable. Ideally, if the data from a previous AJAX request already matches the search query ...

Transforming an ordinary JavaScript object into a class instance

As I was delving into Angular's documentation on "Interacting with backend services using HTTP", I came across the following statement in the "Requesting a typed response" section: ...because the response is a plain object that cannot be automatical ...

Unconventional way of assigning class properties in Typescript (Javascript): '?='

Recently, I came across the ?= assignment expression within a class property declaration. Can anyone provide some insight into what this means? I am familiar with the new Optional Chaining feature (object?.prop), but this particular syntax is unfamiliar t ...

What are some alternative methods for organizing folder structure in Express Handlebars when managing views?

Is there a more efficient way to render HTML files without constantly needing them to have different names? I'm looking for a method where handlebars can identify which file in which folder to render, without encountering conflicts with files of the s ...

Experimenting with JavaScript within an Immediately Invoked Function Expression

My team leader is requesting that I encapsulate my JavaScript code within an Immediately-Invoked Function Expression (IIFE). However, I am struggling to use spyOn in my Jasmine spec file. How can I properly use spyOn on the following: (function(){ fu ...

Retrieving data from a file results in receiving blank strings

Struggling to access the data within a directory of files, I've encountered an issue where the data doesn't seem to be read correctly or at all. Even though there is content when opening the files individually, when attempting to examine their co ...

What is the proper method for initiating an ajax request from an EmberJs component?

Curious to learn the correct method of performing an ajax call from an Ember component. Let's say, for instance: I am looking to develop a reusable component that allows for employee search based on their Id. Once the server responds, I aim to update ...

The current status of the Macrotask and Microtask queues as this calculation is being processed

This particular inquiry delves into a nuanced aspect of the event loop, seeking clarification through a concrete example. While it shares similar characteristics with another question on Stack Overflow, specifically Difference between microtask and macrota ...

Is it possible to extract external JSON data using JQuery's $.getJSON function?

I am trying to retrieve a quote from the iheartquotes website and display it within a div when my webpage loads. However, for some reason, the code I have written is not working as expected. <script type="text/javascript"> $(document).ready( ...

Can you please explain why I am unable to remove the item in my code using Node.js and Express?

Currently, I am in the process of learning NodeJS and working on an application that involves adding Bicicleta objects. However, I have encountered an issue where I am unable to delete these objects successfully. Even though the POST request for deletion r ...

Having trouble loading a CSV file into a static folder using Node.js and Express

As a newcomer to node and express, I am exploring the integration of d3 visualizations into my web page. Essentially, I have a JavaScript file that creates all the d3 elements, which I then include in my .ejs file. I am currently attempting to replicate a ...

What could be causing the onclick function to not activate on the iOS safari browser?

My Shopify site works perfectly on all browsers except iOS Safari. When users try to click the "add to cart" button on this specific browser, it does not trigger the onclick function. This issue is unique to iOS Safari as the button works fine on desktop a ...