Do X till first fail then Y

I am trying to write a function that will iterate through an array with an if statement. I would like the function to perform a differently for each element following the first failure. I have been circling around it for a short while and thought I’d ask for some help.

Below is my current code. Thanks.

function highLight(){
  
  let moneyLeft = document.getElementById('spending').value;
  for (let i =0; i<notesCollection.length; i++){
    if (Number(notesCollection[i].cost) <= moneyLeft){
      notesCollection[i].highlight= true;
      moneyLeft = moneyLeft - notesCollection[i].cost;
    }
    else{
      notesCollection[i].highlight = false;
    }
  }
  loadNotes();
  titleList();
}

What part isn’t working the way you want it to?

Can you explain what you want it to do before the first failure and after the first failure? What does “differently” mean? Also, define what it means to be a “failure”.

I looked back through to try and answer your question and found that I needed to include:

moneyLeft = moneyLeft - notesCollection[i].cost;

to the else statement as well, that way each iteration would impact the rule. thanks for the help.

Congratulations on figuring it out! Happy coding.

1 Like