What is the most efficient way to retrieve an index within a recursive function in JavaScript?

let array = [1, [2, 3, [4, 5, ["six", "seven", 6666, [8, 9, [10]]]]]]
    //1. Identify and access the last element
   //2. Utilize index notation like in **console.log(array[1][2][2][3][2][0]** but should output 
  // [1][2][2][3][2][0] or 1,2,2,3,2,0

Within this function, I have successfully located the last element but now I am struggling to locate the second question (which requires a recursive function)

function findLastElement(arr){
       for (let element of arr ){
          if(typeof element === "object"){
             findLastElement(element)
              console.log(element)
          }
       }
}

findLastElement(array)

Answer №1

If you want to retrieve all the indexes that are less than the last index in an array, you can achieve this by using a recursive function that checks if the last item is also an array:

const getLessIndexes = arr => {
  const last = arr.length - 1
  
  return [
    last,
    ...Array.isArray(arr[last]) 
      ? getLessIndexes(arr[last]) 
      : []
  ]
}

const array = [1, [2, 3, [4, 5, ["six", "seven", 6666, [8, 9, [10]]]]]]

const result = getLessIndexes(array)

console.log(result)

Answer №2

If you want to iterate through an array and get both the index and element, you can use the Array.entries() method.

function findLastObj (arr){
  for (let [index, obj] of arr.entries() ){
    if(typeof obj === "object"){
      findLastObj(obj)
      console.log(obj)
      console.log(index)
    }
  }
}

Answer №3

let numbers = [1, [2, 3, [4, 5, ["six", "seven", 6666, [8, 9, [10]]]]]];

function findLastValue (arr){
  for (let [position, item] of arr.entries() ){
    if(typeof item === "object"){
      findLastValue(item)
      console.log(item)
      console.log(position)
    }
  }
}

console.log( findLastValue(numbers) )

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 difficulty animating camera rotation in ThreeJS with Tween

I am facing an issue with animating the ThreeJS camera rotation using TweenJS. While I can successfully tween the camera position, the camera.rotation does not seem to update as expected. To illustrate my problem, I have created a simple example based on ...

Learn to leverage JavaScript in Node-RED to dynamically display messages based on selected dropdown options

After reviewing this Node-red flow: https://i.stack.imgur.com/y4aDM.png I am struggling with the implementation in my function. There are 3 options in each dropdown, one for meat type and the other for doneness. Once I select a combination from the drop ...

Utilizing a refreshed array of elements within a component directive

When working within a view, I am utilizing ng-repeat inside a directive to iterate over an array of objects from my controller. However, as the objects in the array undergo value changes, I encounter a dilemma when transitioning to a new instance of the sa ...

Test your knowledge of Javascript with this innerHtml quiz and see

How can I display the output of a score from a three button radio button quiz without using an alert popup? I want the output to be displayed within a modal for a cleaner look. I tried using InnerHTML but now there is no output when the button is clicked. ...

I'm puzzled by this C++ array declaration

When you declare an array in C++ like this: int myArray[8] = {0,}; What is the significance of this syntax? ...

Using Reactjs to bind onClick event to a list component generated dynamically

If I have a render function that resembles the following: render() { var user_rows = [] this.state.user_list.forEach((user, index) => { user_rows.push( <tr key={user}> <td><div className="bt ...

What is the reason behind Angular's refusal to automatically bind data when an object is cloned from another object?

Check out this simple jsfiddle I made to demonstrate my question: fiddle Here is the HTML code snippet: <div ng-controller="MyCtrl"> <div ng-repeat="p in products"> <span ng-click="overwrite(p)">{{ p.id }}: {{ p.name }}& ...

Is it possible to include multiple API routes within a single file in NextJS's Pages directory?

Currently learning NextJS and delving into the API. Within the api folder, there is a default hello.js file containing an export default function that outputs a JSON response. If I decide to include another route, do I need to create a new file for it or ...

What is the best way to invoke a function with multiple parameters in TypeScript?

I have a function that manipulates a specified query string, along with another version that always uses window.location.search. Here is the code snippet: class MyClass { public changeQuery(query: string; exclude: boolean = true; ...values: string[]): st ...

Creating a series of values to populate a column in a data frame

Imagine having a data set called "Address" structured like this: Street HouseNumber A Fakestreet1 10 bla Fakestreet2 20 bla Fakestreet3 30 bla Fakestreet4 40 bla You want to introduce a new ...

What is the process for identifying a potential group of k elements from an array?

I need help finding all possible combinations of k elements from an array that has 10 elements. The value of k is dynamic, meaning it can vary. The code provided below works for finding combinations of 4 elements, but I need a solution that can handle an ...

Exploring elementary functionalities within PHP

I'm just starting out, so please excuse any confusion in how I phrase this. Currently, I'm diving into my online computer science course which is focused on functions. The task at hand is to create sentences that output three different variables ...

Adjust div size when the window size changes

I am facing an issue where the 5 divs fit well when the content is initially loaded, but if I resize the window, the size of the containers no longer align with the layout. For my layout, I am using Isotope and the following script to adjust the images to ...

Issues encountered when attempting to implement Ajax with Node.js and Express.js

Trying to transfer data from the server side to the client side using ajax has been challenging. When utilizing res.send(data) in Node, it displays an empty HTML with the data. I aim to retrieve data from the client side without reloading the page and maki ...

Updating columns in MongoDB using arrays in JavaScript has just gotten easier

When trying to update a mongoDB collection with an array value, the update fails without any error message. This method causes the issue: var arr = ["test","test1","test2"]; $.ajax('http://my.mongodb.com/collection?id=80a2c727de877ac9' , { ...

Harness the power of electrons with the simple push of a button - initiating program execution

Recently, I delved into Electron with the desire to create a small application for myself. This app would allow me to run different programs or games by simply clicking on a link. My goal is to have the program/game start automatically when I open the Ele ...

Determine the width of the containing element using Vue.js

I have been working on implementing a Vue.js component called CamViewMatrix. My goal is to retrieve the width of CamViewMatrix's parent element within the component itself (specifically in the created() method of CamViewMatrix), in order to perform so ...

Utilizing additional PHP files to handle the AJAX post request and subsequently execute the PHP script

I have been tasked with a complex assignment that I am struggling to comprehend. Let me provide a brief overview of what is required of me. There are three files involved in this task: 1. An HTML file that sends an AJAX post request to passwrapper.php. 2. ...

Arrow smoothly sliding beneath the selected tab in the active menu

Here is a reference picture. https://i.sstatic.net/wsp6R.png I am trying to create a slide effect for my arrow when clicking on different menu items. The arrow should move over the active menu item. By default, the arrow should point to the active menu. ...

Leveraging Javascript Modules within a Typescript Vue Application

The issue at hand I've encountered a problem while attempting to integrate https://github.com/moonwave99/fretboard.js into my Vue project. My initial approach involved importing the module into a component as shown below: <template> <div&g ...