2

I've created a function called checkLength(input, min, max) which takes in a username and password input as shown below.

checkLength(username, 3, 15);
checkLength(password, 8, 25);

However, I'm looking to pass in an inputArray, minArray, maxArray to reduce the repetitiveness using a forEach loop. But it seems like a forEach loop can only take in one array at a time. Any suggestions on how I can improve this?

checkLength2([username,password], [3,8], [8,15])

function checkLength2 (inputArray, minArray, maxArray, i=0) {
inputArray.forEach(input => {
    if (input.value < minArray[i]) {
        //another error function
        i++;
    }
});}
3
  • 7
    I think you original approach with two function calls makes a lot more sense Commented Sep 30, 2020 at 5:24
  • 1
    [[username, 3, 8], [password, 8, 15]].forEach(args => checkLength(...args)); is an approach. Commented Sep 30, 2020 at 5:53
  • I'm looking to pass in an inputArray, minArray, maxArray and now you have 3 lists that you need to maintain and keep in sync Commented Sep 30, 2020 at 6:12

2 Answers 2

1

You should try index from forEach loop.

function checkLength2 (inputArray, minArray, maxArray) {
  inputArray.forEach((input, i) => {
      if (input.value < minArray[i]) {
          // do something
      } else if (input.value > maxArray[i]) {
          // do something else
      }
  });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This was exactly what I was looking for.
1

if you want to show the same message you can try this out. or else you can use if/else statement for checking both the minArray and maxArray

function checkLength2(inputArray, minArray, maxArray, i = 0) {    
  for (let index = 0; index <= inputArray.length; index++) {    
    if (inputArray[index].value < minArray[index] && inputArray[index].value>maxArray[index]) {    
      //error
    }
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.