Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
how i can get index in recursive function in javascript?
let array = [1, [2, 3, [4, 5, ["six", "seven", 6666, [8, 9, [10]]]]]]
    //1.find last element
   //2. index way like in **console.log(array[1][2][2][3][2][0]** but should print 
  // [1][2][2][3][2][0] or 1,2,2,3,2,0

in this function i find last element now i can't find the 2nd question (it should be recursive function )

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

findLastElement(array)
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can use a recursive function to always take the last index, and continue if the the last item is an array as well:

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)

about 4 years ago · Juan Pablo Isaza Report

0

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

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

console.log( findLastElement(array) )

about 4 years ago · Juan Pablo Isaza Report

0

You can use Array.entries()

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!