0

I have a code with too many if conditions. So, I want to convert this code to foreach loop but somehow it's not working.

if (str_array[0] === "1" || str_array[1] === "1" || str_array[2] === "1" || str_array[3] === "1" || str_array[4] === "1" || str_array[5] === "1" || str_array[6] === "1" || str_array[7] === "1" || str_array[8] === "1" || str_array[9] === "1" || str_array[10] === "1" || str_array[11] === "1") {
    column_data[0].hidden = false;
}
if (str_array[0] === "2" || str_array[1] === "2" || str_array[2] === "2" || str_array[3] === "2" || str_array[4] === "2" || str_array[5] === "2" || str_array[6] === "2" || str_array[7] === "2" || str_array[8] === "2" || str_array[9] === "2" || str_array[10] === "2" || str_array[11] === "2") {
    column_data[1].hidden = false;
}

I have total 12 if statements with or condition.

for (var i = 1; i <= 12; i++) {
    console.log('"' + i + '"');
    if (str_array[0] === '"' + i + '"' || str_array[1] === '"' + i + '"' || str_array[2] === '"' + i + '"' || str_array[3] === '"' + i + '"' || str_array[4] === '"' + i + '"' || str_array[5] === '"' + i + '"' || str_array[6] === '"' + i + '"' || str_array[7] === '"' + i + '"' || str_array[8] === '"' + i + '"' || str_array[9] === '"' + i + '"' || str_array[10] === '"' + i + '"' || str_array[11] === '"' + i + '"') {
        console.log(i - 1);
        column_data[i - 1].hidden = false;
    }
}

Loop is executing properly and I got value. "1","2","3","4","5" etc. in console.log('"'+i+'"');.

But somehow it's not working. It's working with static code but when I put it in loop it's not working. Is there any difference in qoutes values which I'm getting in for loop and static.

1
  • So you want to know if any of the array values is equal to 1 right? Commented May 8, 2018 at 12:14

2 Answers 2

3

You can try following

for(var i=1;i<=12;i++) {

  if(str_array.includes(i.toString())) { // converting number to string
     column_data[i-1].hidden = false;
  }
}

For reference, Array.includes

Sign up to request clarification or add additional context in comments.

1 Comment

Oh great. That's what I need. Thank you for this quick reply.
1

You can run another loop based on str_array length

str_array.some( s => s == i ) //== will work fine for 1 == "1"

Finally

for(var i=1;i<=12;i++)
{
   var flag = str_array.some( s => s == i ) ;
   if( flag ) 
   {
      column_data[i].hidden = false;
   }
}

If you want to set the value of hidden property to true, if all values are not as per index, then directly assign the flag to hidden property

for(var i=1;i<=12;i++)
{
    column_data[i].hidden = str_array.some( s => s == i );
}

1 Comment

Sure, glad to help.

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.