Tobbe
Tobbe

Reputation: 55

Replace multiple if statements with loop?

Can this code be shortened by looping through the array and replacing the number in input[name="shelf-1"] instead of having multiple if statements?

if(com_array[0] == "ON")
{
    $('input[name="shelf-1"]').bootstrapSwitch('state', true);
}else{
    $('input[name="shelf-1"]').bootstrapSwitch('state', false);
}

if(com_array[1] == "ON")
{
    $('input[name="shelf-2"]').bootstrapSwitch('state', true);
}else{
    $('input[name="shelf-2"]').bootstrapSwitch('state', false);
}

if(com_array[3] == "ON")
{
    $('input[name="shelf-3"]').bootstrapSwitch('state', true);
}else{
    $('input[name="shelf-3"]').bootstrapSwitch('state', false);
}

Upvotes: 2

Views: 518

Answers (4)

Isaac Yong
Isaac Yong

Reputation: 109

Assuming that you want to do this for all elements inside the array, you can use a forEach loop as so:

com_array.forEach( (element, index) => {
    if(element == "ON") {
        $(`input[name="shelf-${index + 1}"]`).bootstrapSwitch('state', true);
    }else{
        $(`input[name="shelf-${index + 1}"]`).bootstrapSwitch('state', false);
    }
})

Updated for refactoring option:

If you want it to be cleaner and less repetitive, you can do away with the if-else statement, and use "element == 'ON' as the condition inside bootstrapSwitch:

 com_array.forEach( (element, index) => {
        $(`input[name="shelf-${index + 1}"]`).bootstrapSwitch('state', element == "ON");
})

And then you can refactor further to one line

com_array.forEach((element, index) => $(`input[name="shelf-${index + 1}"]`).bootstrapSwitch('state', element == "ON"))

Upvotes: 2

AMakarov
AMakarov

Reputation: 329

com_array.forEach(function(com, index) {
        $('input[name="shelf-' + (index + 1) + '"]').bootstrapSwitch(
            'state',
            com == 'ON'
        )
    }
);

I made it IE-11 compatible (i.e. no arrow functions and string template literals). Because I assume you have no transpilation step.

For the non-IE compatible answer (modern js) check the first comment to the question with code.

Upvotes: 1

Zam Abdul Vahid
Zam Abdul Vahid

Reputation: 2721

You can replace the numbers using the index of the array.

let com_array = ['ON','OFF','ON'];
for (index = 0; index < com_array.length; index++) {
  if (com_array[index] === 'ON') {
    $('input[name="shelf-'+(index+1)+'"]').bootstrapSwitch('state', true);
  } else {
    $('input[name="shelf-'+(index+1)+'"]').bootstrapSwitch('state', false);
  }
}

Upvotes: -1

Alexey Yevtushok
Alexey Yevtushok

Reputation: 21

You could create a function and reuse it:

const bootstrapSwitch = (key, value) = {
  $(`input[name="shelf-${key}"]`).bootstrapSwitch('state', value);
}

bootstrapSwitch(0, com_array[1] == "ON")
bootstrapSwitch(1, com_array[2] == "ON")
bootstrapSwitch(3, com_array[3] == "ON")

Upvotes: 0

Related Questions