2 for loops confusion

function barista(coffees){
  const coff=coffees.sort(function(a, b){return a - b})
  let time=0
  for (let i=0; i<coff.length;i++) {
      time+=coff[i]
      for (let j=0; j<i;j++) {
        console.log(coff[j])
          time += coff[j]+2;
      }
  }
  return time
}
barista([4,3,2])

I understood that coff[i] gives me 2, 3 ,4. But I don’t understand why coff[j] gives me 2, 2, 3. Where exactly did those numbers come from?

Because that is what is happening on the different iterations of i. Try it this way:

function barista(coffees){
  const coff=coffees.sort(function(a, b){return a - b})
  console.log('coff', coff)
  let time=0
  for (let i=0; i<coff.length;i++) {
    console.log(`*   i=${i}`, `  coff[${i}]`, coff[i])
      time+=coff[i]
      for (let j=0; j<i;j++) {
        console.log(`*** j=${j}`, `  coff[${j}]`, coff[j])
          time += coff[j]+2;
      }
  }
  return time
}
barista([4,3,2])
1 Like