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

Multer is experiencing difficulties in uploading files, yet it is not displaying any error messages

When setting up an application to create courses with images, I encountered an issue while using multer for image uploading. Despite adding multer to my route with upload.single('images'), the uploaded images were not appearing in the designated ...

What is the best way to access a custom object in JavaScript that was created in a different function?

Currently working with JavaScript and jQuery technology. In one of my functions that runs on document ready, I am creating objects with different attributes. While I can easily access these object attributes within the same function, I'm facing diff ...

Ensuring that EJS IF/ELSE statements are evaluated accurately

I am encountering an issue where my variable 'answer' is returning the string 'success' and displaying correctly in the view. However, the IF/ELSE statement always seems to evaluate to the ELSE condition and displays 'no' inst ...

Adding clickable padding to a Draft.js editor can enhance the user experience and make the editing process

Is there a way to apply padding to the Draft.js Editor so that clicking on the padding area selects the Editor? If I add padding directly to the container div of the Editor, the padding displays properly but clicking on it does not enable writing in the E ...

how to set a variable's value outside of a Promise using internal code

export class YoutubeService { getTrendingVideos(country) { let result = []; return axios.get('/').then(function(res){ result = res.data.items; for (var i = 0; i < result.length; i++) { result[i] = { id: ...

Is there a way to execute two files concurrently in JavaScript using node.js?

I'm a beginner in the world of Javascript and Node.js, and I've encountered some issues while trying to test code I recently wrote. Specifically, I am attempting to test the code within a file named "compareCrowe.js" using another file named "tes ...

Manipulating nested arrays using index values in JavaScript

Can someone assist me in sorting a multidimensional array based on the value of the first index? I've tried using a for loop without success. Looking for solutions in JS or jQuery. I want to convert the following array: var pinData = [ ['< ...

How can I manually transclude content within a directive into two separate locations?

When trying to access the result of ng-repeat, I discovered that using the transclude function and manually compiling could help. However, this method does not work in situations with two places and elements containing ng-repeat. Here is how my code is str ...

The slideshow fails to show correctly after being loaded from an external JavaScript file

Utilizing standard code, I have set up a Slideshow at the top of a website: HTML: <body id="Top" onload="showSlides()"> ... <div id="slides"> <div id="slide1" class="slides fade"></div> <div id="s ...

How can I transfer data from two queries to Jade using Node.js (Express.js)?

I have a database with two tables - one for storing user information and another for managing friendship connections: setting up a friend list in mysql My goal is to create a profile page using Jade, specifically profile.jade: - each user in users ...

What is the standard approach for exchanging localized user interface strings between Microsoft's MVC and JavaScript?

In the process of developing an application that utilizes a dynamic, javascript-based client, I am facing the need for localization. This particular application includes significant UI components that are not generated by Javascript and are instead served ...

Can I send a DELETE request with request body and headers using Axios?

When working with Axios in ReactJS, I am attempting to send a DELETE request to my server. In order to do this, I need to include the following headers: headers: { 'Authorization': ... } The body of the request consists of: var payload = { ...

Executing an http.get request in Angular2 without using RxJS

Is there a method to retrieve data in Angular 2 without using Observable and Response dependencies within the service? I believe it's unnecessary for just one straightforward request. ...

React Native error - "Invalid element type: expected a string or class/function, but received undefined" - encountering issue with importing a custom library?

Alright, I'm looking to make some modifications to this library, so I am attempting to import the non-transpiled version by downloading the repository and importing it from here: https://github.com/nicotroia/react-native-floating-action-menu#readme A ...

Swapping out the main view for the partial view

Recently, I wrote some jQuery code to fetch data from an action by passing in a dashID. The expected result was to receive HTML containing the relevant information. Unfortunately, my jQuery script is not returning the desired data. Below is the JavaScript ...

Error Message: jQuery script imported successfully, however, functions are not defined

Here is my HTML code: <script type="text/javascript" src="js/myjs.js"></script> <script> ... $("#enviornment").hide().delay(1200).css({'display':'block', 'opacity':'0'}).animate({'opacity&apos ...

What is the process for updating the package-lock.json file in Laravel?

GateLab's security feature has identified some known vulnerabilities in the package-lock.json file that need to be updated. The message states: Known security vulnerabilities detected Dependency object-path Version < 0.11.5 Upgrade to ~> 0.11. ...

How can I retrieve the data passed in a post request using Azure Functions and JavaScript?

I have a JavaScript Azure function that takes a context and request as parameters: function(context, req) It's easy to retrieve data from a GET request using the req object. For example, if I pass name=test in the URL, I can retrieve it in my code l ...

"Enhance your web app with Emotion.js and Preact SSR, complete with

In my preact SSR application, I have utilized Emotion JS 10 for styling purposes. My goal was to incorporate RTL support into the app. To achieve this, I implemented createEmotion and createEmotionServer, leveraging the resulting renderStylesToString to r ...

Is there a way for my code to detect when a function and a timeout are in progress?

Is there a way to disable my button after just one click, or when the timeOut function is running? Currently, I have code that allows the button to be clicked only if my moneyValue is greater than money, and it's working perfectly. Now, within that sa ...