Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find last element in array from a specific index

Im trying to make a function that will navigate the user to the steps that are not disabled, and that skips the disabled steps.

I wrote the following code, but it does not behave how i would like it to.

Expected behaviour assuming the current step is Step 5:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

On Button Click Step 5 to Step 3 on Button click Step 3 to Step 1

But currently the behaviour is like this:

On button click Step 5 to Step 1

I want to make the loop the stop on step 3, i tried to add a breakpoint, but that did not solve it, i am running out of ideas

 const steps = [
  { title: 'Step 1', id: 'stp1', disabled: false, },
  { title: 'Step 2', id: 'stp2', disabled: true,  },
  { title: 'Step 3', id: 'stp3', disabled: false, },
  { title: 'Step 4', id: 'stp4', disabled: true,  },
  { title: 'Step 5', id: 'stp5', disabled: false, },
]

const [currentStepIndex, setCurrentStepIndex] = useState(4);

const getPreviousSelectableStep = () => {
  const steps = args.steps
  let stepIndex = currentStepIndex

  if ((stepIndex > 0) && steps[stepIndex - 1].disabled === true) {
    for (var i = steps.length - 1; i >= 0; i--) {
      if (steps[i].disabled === false) {
        setCurrentStepIndex(i)
        setCurrentStepId(steps[i].id)
        break
      }
    }
  } else if (stepIndex > 0) {
    setCurrentStepIndex(stepIndex - 1)
    setCurrentStepId(steps[stepIndex - 1].id)
  }
}

>Solution :

In your if condition start the loop from startIndex - 1 and not from the end steps.length - 1.

  if (stepIndex > 0 && steps[stepIndex - 1].disabled === true) {
    for (var i = stepIndex - 1; i >= 0; i--) {
      if (steps[i].disabled === false) {
        setCurrentStepIndex(i);
        setCurrentStepId(steps[i].id);
        break;
      }
    }
  } else if (stepIndex > 0) {
    setCurrentStepIndex(stepIndex - 1);
    setCurrentStepId(steps[stepIndex - 1].id);
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading