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

85
Views
Function invoked inside its body in for loop takes last value instead of sequence value

I have an array of objects:

this.array = [{name: null}, {name: null}, {name: null}]

and array of reservend names:

this.reserved = ["name2", "name3"]

I loop through array and try to set uniques name (not included inside reserved array)

  for (let i = 0; i < array.length; i++) {
    this.setDefaultName(array[i], 1);
  }

  private setDefaultName(obj, index){
    if (!this.reserved.includes(`name${index}`)) {
      obj.name = `name${index}`;
      this.reserved.push(`name${index}`);
    } else {
      return this.setDefaultName(obj, index + 1);
    }
  }

After that all objects from array have name "name3". The expected result is to have sequence unique name: "name1", "name4", "name5". Could anyone help me?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

I created a StackBliz demo which is as close as possible to your code and it is actually working fine! You may compare this demo with yours: StackBliz Demo

about 4 years ago · Juan Pablo Isaza Report

0

I adjust some of your code to make it runnable on snippet. It looks like it works though. Can you recheck?

let nameArray = [{name: null}, {name: null}, {name: null}]
let reserved = ["name2", "name3"]

for (let i = 0; i < nameArray.length; i++) {
  setDefaultName(nameArray[i], 1);
}

function setDefaultName(obj, index){
  if (!reserved.includes(`name${index}`)) {
    obj.name = `name${index}`;
    reserved.push(`name${index}`);
  } else {
    return this.setDefaultName(obj, index + 1);
  }
}

console.log(nameArray)

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!