create array based on number of html elements

My goal is to change the value of activeindex in each of the button elements based on a conditional statement. There are 5 buttons if the flag is true, and there should be 4 when false. However I need to calculate the activeIndexes basedon the condition, instead of them being hardcoded. Example: when the flag is off then the last button should have an activeindex of 3, not 4. I imagine I will loop or create a array but little stuck.

let flag = true;
let links = document.getElementsByClassName('link');

<button class='link' activeIndex={0} />
<button class='link' activeIndex={1} />
{#if flag}
<button class='link' activeIndex={2} />
{/if}
<button class='link' activeIndex={3} />
<button class='link' activeIndex={4} />

>Solution :

One really dirty fix would be to just add 1 conditionally (do not do this):

{#if flag}
  <button class='link' activeIndex={2} />
{/if}
<button class='link' activeIndex={2 + (flag ? 1 : 0)} />
<button class='link' activeIndex={3 + (flag ? 1 : 0)} />

With an array you can do something like:

<script>
    let flag = true;
    
    $: links = [
        { data: 'a', show: true },
        { data: 'b', show: true },
        { data: 'c', show: flag },
        { data: 'd', show: true },
        { data: 'e', show: true },
    ].filter(x => x.show);
</script>

{#each links as link, i (link)}
    <button>
        Button {link.data} Index: {i}
    </button>
{/each}

REPL

{#each} provides its own index, so you just have to add/remove the respective item to/from the array.

Leave a Reply