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

63
Views
Loop jumps one element

I'm writing a function that breaks down change into denominations and returns the updated register after change has been given. So far it's working but only if the register has enough money in the respective denominations. If the change is [ 10, 4, 0.5, 0.05 ] as in this case and there are no 10 dollar bills in the register for example, the loop should move on to 5 dollar bills and check if change can be given from those and so on. But what it does instead is it jumps right to 1 dollar bills. What am I missing here? As for indexes, those are pre-calculated in my greater function, so 10 starts going through the loop at index 2 since all denominations before that are greater than 10, 4 starts looping at index 4 since that is the index of 1 dollar bills in the cash register, and so on.

let change = [ 10, 4, 0.5, 0.05 ]
let denomin = [ 100, 20, 10, 5, 1, 0.25, 0.1, 0.05, 0.01 ]
let register = [ 100, 60, 0, 55, 90, 4.25, 3.1, 2.05, 1.01 ]
let idx = [ 2, 4, 5, 7 ]

function test(ch, reg, idx) {
    for (let x of ch) {
        for (let i = idx[ch.indexOf(x)]; i < reg.length; i++) {
            if (reg[i] - x >= 0) {
                reg[i] -= x
                break;
            } else if (reg[i] - x < 0) {
                i++
            }
        }
    }
    return reg = reg.map(a => Number(a.toFixed(2)))
}

console.log(test(change, register, idx))

about 4 years ago · Juan Pablo Isaza
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!