Home > database >  how i can get index in recursive function in javascript?
how i can get index in recursive function in javascript?

Time:10-25

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)

CodePudding user response:

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)
    }
  }
}

CodePudding user response:

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) )
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related