How do I retrieve distinct values from Math.random in JavaScript and prevent them from repeating?

I am attempting to fetch HTML dom elements remotely from a website using jquery/javascript. These elements are stored in an array and are unique, however, when I attempt to display them by generating random indexes with math.random() * my array.length, I notice duplicates occurring. I need to ensure that imgIdx remains unique.

For the purpose of aiding me in understanding this issue better, could someone assist me in identifying what I might be overlooking here?

myarray = [
{ thumb : "http://url.com/img1.jpg", big : "http://url.com/img51.jpg" },
{ thumb : "http://url.com/img61.jpg", big : "http://url.com/img671.jpg" },
{ thumb : "http://url.com/img666.jpg", big : "http://url.com/img371.jpg" },]

function addSomeImages(limit) {
    for (var i = lastIdx; i < lastIdx + limit; i++) {
        var imgIdx = Math.floor(Math.random() * myarray.length);
        $('#endless-gallery').append('<a data-fancybox="gallery" href="' + myarray[imgIdx].big + '">' + '<img class=photo src="' + myarray[imgIdx].thumb + '' +
            '" />' +
            '</a>');
    }

Answer №1

One aspect that hasn't been addressed is the reason why your current solution is failing or why rearranging your array might be a better option. Your current code simply generates a random index to access elements in the array, similar to rolling a die where repeats are more likely than getting unique numbers each time. This randomness is key to (pseudo-)random number generation, ensuring unpredictable results.

To retrieve elements from the array randomly without repeating, you need to prevent duplicates intentionally. Two effective ways to achieve this are:

1) Shuffling the array and iterating through it as suggested in the comments of your question.

2) Removing accessed elements from the array and looping until it's empty.

Shuffling the array stands out as the preferred method since it doesn't alter or destroy the original array like removing elements does. Here's why shuffling works while your initial approach doesn't:

Shuffling maintains the original elements but in a randomized order, much like shuffling a deck of cards. As you go through the shuffled list, there's no chance of encountering a card twice.

On the other hand, removing items from the sorted array ensures each picked element is unique, preventing duplicates. As long as an item is removed from the array after being selected, you won't encounter it again.

Your current method involves selecting a random card from a sorted deck, looking at it, and returning it to its original place before picking another - increasing the likelihood of revisiting the same card.

The recommended approach involves using the Fisher-Yates shuffle function mentioned in the comments:

function shuffle(array) {
    var currentIndex = array.length, temporaryValue, randomIndex;

    while (0 !== currentIndex) {

        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }

    return array;
}

You can implement it like this:

myarray = [ ... ];
myarray = shuffle(myarray);

function addSomeImages(limit) {
    for (var i = lastIdx; i < lastIdx + limit; i++) {
        $('#endless-gallery').append('<a data-fancybox="gallery" href="' + myarray[i].big + '"><img class="photo" src="' + myarray[i].thumb + '" /></a>');
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trigger JavaScript when a specific division is loaded within a Rails 4 application

Is there a way to trigger a JavaScript function when a specific div with a certain class is loaded within my Rails 4 application? <div class="myClass"> hello world </div I am looking for a solution to execute some JavaScript code only when t ...

creating a personalized CSS style rule

Can a custom rule be created in CSS using @media for a parent class to make changes based on the class? <div class="parentGreen"> <ul class="ul1"> <li>1</li> <li>2</li> &l ...

Protractor successfully opens Firefox, however no URL is loaded. Chrome, on the other hand, functions perfectly

Every time I attempt to execute my protractor tests on Firefox, the browser opens but no URL is loaded. Eventually, an error message appears in the command prompt: Using FirefoxDriver directly... [launcher] Running 1 instances of WebDriver ERROR - Unabl ...

Unforeseeable actions when assigning memory within a structure

As a C beginner, I am eager to understand how memory allocation and pointers function. However, I am encountering some unexpected behavior in my code. Review the code snippet and resulting output below to see the issue at hand. I am currently using Mingw w ...

Implementing a download hyperlink attribute for a button with jQuery

How can I create a jQuery function for a button? <input type="submit" id="submit"></input> Once clicked, it should trigger the following action: <a download href="file.doc"></a> <script> $("#submit").click(function(){ ...

Using jQuery Modal Dialog with ASP.NET MVC 2

In my ASP.NET Mvc 2 application, I have a grid of user info. When a user is clicked, a jQuery Modal dialog opens allowing me to edit and save the user's information successfully. I am now looking for assistance on implementing validation on this moda ...

Modifying canvas border colors using AngularJS

Currently, I am in the process of learning AngularJS and have developed a website that includes a canvas element. My main objective is to change the border color after clicking on a checkbox. Here is the code snippet for canvas.html : <!DOCTYPE html&g ...

I possess multiple checkboxes that appear as described below. I am looking to modify the nested value highlighted in the blue circle in the image

I need to make a change in this area of my state: view screenshot The specific portion highlighted in the circle is what I want to modify **Here is my checkbox input code:** {this.state.data.map((elm) => ( <div className={classes.rowContainer}&g ...

Instruction failed to produce HTML output

Currently facing a challenge with my code - I have a dynamically created span (via ng-repeat). <span my-size id="abc"></span> <span my-size id="def"></span> <span my-size id="ghi"></span> The goal is to extract the id ...

I'm wondering if there is a method for me to get only the count of input fields that have the class "Calctime" and are not empty when this function is executed

Currently, I am developing an airport application that aims to track the time it takes to travel between different airports. In this context, moving from one airport to another is referred to as a Sector, and the duration of time taken for this journey is ...

Customize your Jquery UI Calendar with Changing Background Images for Each Month!

How can I change the background of jQuery UI datepicker based on the selected month? I have created 12 classes, each representing a month, and the selected month already has the background. I tried using "onChangeMonthYear: function(year, month, inst) { ...

How can I manage the asynchronicity of Hapi.js, fs.readFile, fs.writeFile, and childProcess.exec?

My code execution seems to be resulting in an empty list, could it be that my asynchronous calls are incorrect? I've tried rearranging and breaking things into functions but there still seems to be a timing issue with my execution. The order in which ...

Dealing with the 404 error for a missing resource in ocLazyLoad

I am seeking guidance on how to handle resource loading errors in ocLazyLoading. I have attempted to load some resources within the resolve section of my $stateProvider. One file, ctrl.js, loads successfully. However, another file, iam-not-there.js, fails ...

Can Microsoft Edge Developer tool be used to incorporate external programs or code?

This image of msedge-devtools clearly demonstrates my point. I am interested in building a webpage parser using selenium and Microsoft Edge, beyond just JavaScript. I am seeking a way to utilize the Microsoft Edge developer tools (Inspect Element Mode) t ...

Dealing with Errors When Working with Angular Promises

Currently, I am in the process of mastering promises within Angular. In my code snippet, I have two "GET" requests that I need to execute sequentially. Everything is functioning properly, but I'm unsure about how to handle errors in this scenario. If ...

Set the minimum date for the jQuery datepicker

Having trouble with jQuery datepickers for selecting from and to dates? Currently, the code restricts the selection in the second datepicker to dates after the one selected in the first datepicker. However, what if you need to set the to datepicker to allo ...

The JavaScript replace function using regex eliminates additional content

There is a content string that includes full YouTube URLs and video IDs. I need to replace the URLs with just the video IDs. The example of the "content" variable: var content = '{GENERICO:type="youtube",id="DluFA_AUjV8"}{GENERICO:type="youtube",id ...

Using the codesnippet feature in CKEditor in combination with highlight.js

I am currently experimenting with implementing the highlight.js library in conjunction with the CKEditor addon called CodeSnippet. Although I have successfully integrated the CodeSnippet addon into my CKEditor, the code is not being properly detected, col ...

Is there a way to modify the value of an object in a Vuex store using actions in Vue.js?

I have data stored in an array within the state and I need to update a specific object. How can I change the value of the object with id 1 to true using Vuex actions? state.js const array=[] mutations.js storeArray(state, data) { state.array = data ...

No content appears on the multi-form component in React

After several attempts at building a multi-step form in React, I initially created a convoluted version using React.Component with numerous condition tests to determine which form to display. Unsatisfied with this approach, I decided to refactor the code f ...