2

I am trying to develop a simple banner rotation with javascript.

How can I make sure that only arrays with the value "active": 1 are included in the shuffle?

<div id="ad-container"></div>
<script>
var banner = [{
        "img": "https://DOMAIN.TLD/IMG.JPG",
        "url": "https://LINK.DOMAIN.TLD",
        "maxWidth": 468,
        "active": 1
      },
      {
        "img": "https://DOMAIN.TLD/IMG2.JPG",
        "url": "https://LINK2.DOMAIN.TLD",
        "maxWidth": 468,
        "active": 0
      }
,
      {
        "img": "https://DOMAIN.TLD/IMG3.JPG",
        "url": "https://LINK3.DOMAIN.TLD",
        "maxWidth": 468,
        "active": 1
      }
    ];

function shuffle(banners) {
      var j, x, i;
      for (i = banners.length - 1; i > 0; i--) {

        j = Math.floor(Math.random() * (i + 1));
        x = banners[i];
        banners[i] = banners[j];
        banners[j] = x;
      }
      return banners;
    }

    shuffle(banner);

document.getElementById('ad-container').innerHTML = '<a href="' + banner[0]["url"] + '"><img src="' + banner[0]["img"] + '" style="width: 100%;height: auto;max-width: ' + banner[0]["maxWidth"] + 'px;"></a>';

</script>

All arrays with the value "active": 0 should not be included in the shuffle.

Maybe somebody knows how to improve the shuffle/code or how to prevent that the same banners from being displayed more than once on a page if there are more document.getElementById includes on the same page.

Thanks in advance.

OMEXLU
  • 65
  • 1
  • 6

1 Answers1

3

Just filter the array.

var banner = [{
        "img": "https://DOMAIN.TLD/IMG.JPG",
        "url": "https://LINK.DOMAIN.TLD",
        "maxWidth": 468,
        "active": 1
      },
      {
        "img": "https://DOMAIN.TLD/IMG2.JPG",
        "url": "https://LINK2.DOMAIN.TLD",
        "maxWidth": 468,
        "active": 0
      }
,
      {
        "img": "https://DOMAIN.TLD/IMG3.JPG",
        "url": "https://LINK3.DOMAIN.TLD",
        "maxWidth": 468,
        "active": 1
      }
    ];
    
    let activeParts = banner.filter( info => info.active );
    
    console.log( activeParts ); 

    // do whatever, e.g.:
    // shuffle( activeParts );
Rob Monhemius
  • 4,822
  • 2
  • 17
  • 49