Select three unique numbers at random from the total number of elements in the array

I currently possess an array containing a variety of objects. At present, there are 21 objects in this array, although this number is subject to change.

To iterate through the array and generate the necessary content, I am implementing the following code snippet:

for (let i = 0; i < projects.length; i++) { 
let imagesString = projects[i].images.reduce((acc,image,ind)=>{
if (ind==0) return acc;
return acc +'<a href="' + projects[i].imagelocation + image + '" data-fancybox="' + projects[i].fancybox + '" data-caption=" ' + projects[i].description + '"></a>'},"");

content += '<div class="galleryitem col-lg-4 col-md-4 col-sm-6 ' + projects[i].category + '"><a href="' + projects[i].imagelocation + projects[i].images[0] + '" data-fancybox="' + projects[i].fancybox + '" data-caption=" ' + projects[i].description + '"><div class="h_gallery_item"><div class="g_img_item"><i class="fas fa-expand expand"></i><img class="img-fluid" src="' + projects[i].imagelocation + projects[i].thumbnail + '" alt="' + projects[i].name + ' - ' + projects[i].subheading + '"></div><div class="g_item_text"><h4>' + projects[i].name + '</h4><p>' + projects[i].subheading + '</p></div></div></a>'+imagesString+'</div>';    
}

In another area of the web application, my aim is to randomly select 3 unique objects from this array and showcase them. Instead of using

let i = 0; i < projects.length; i++
, I require 'i' to be replaced with 3 distinct random numbers within the range of projects.length.

Answer №1

Wow, this code is perfectly tailored for my needs:

const selectedProjects = [];
for(let count = 0; count < 3; count++) {
    const randomIndex = Math.floor(Math.random() * projects.length);
    if (!selectedProjects.includes(randomIndex)) {
        selectedProjects.push(randomIndex)
    } else {
      count--
    }
};

Answer №2

let newArray = []     // Initialize a new array
let randomIndexes = [] // Array to store 3 random indexes from the original array

for(let j = 0; j < 3; j++) {
   randomIndexes.push(Math.floor(Math.random() * arr.length))
}

console.log(randomIndexes)

UPDATE: There is a possibility of repeated values in the smaller arrays, but this improves as the array size increases.

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

ObjectArray in Node.js

Building an object array in my node app involves transforming another object array. Let's assume the initial object array is structured like this... levels: [ { country_id: 356, country_name: "aaa", level0: "bbbb", level1: "cccc", level2: "dddd", le ...

Troubleshooting issues with JavaScript events in order to effectively implement popovers

I am facing an issue on a webpage that contains a significant amount of JavaScript. The Twitter bootstrap's popover widget is not functioning as expected. Specifically, when I hover over the icon that should trigger the "popover," nothing happens. I h ...

Changing the appearance of a specific child component in React by referencing its id

There is an interface in my code. export interface DefaultFormList { defaultFormItems?: DefaultFormItems[]; } and export interface DefaultFormItems { id: string; name: string; formXml: string, isDefaultFormEnable: boolean; } I am looking ...

Using jQuery to reference my custom attribute---"How to Use jQuery to reference My

Can you explain how to reference a tag using a custom attribute in jQuery? For example, if I have a tag like this: <a user="kasun" href="#" id="id1">Show More...</a> I want to reference the tag without using the id. So instead of using: $( ...

Modifying element information in JavaScript for a Django/Heroku web application

Is it possible for me to update the values of a data object within my JavaScript code? My JavaScript receives post messages from an iframe, and I need to store this information in the correct objects. However, I am unsure if this can be done on the HTML su ...

Adjusting an image size using JQuery after resizing a canvas will only resize the image itself, not

How can I resize an image within a canvas using JQuery in a way that only the image is resized, not the entire canvas? function resizeImage(width, height){ var image = document.getElementById('resizeImage'), canvas = document.createEleme ...

Combining Arrays in MATLAB by Matching Specific Columns

After obtaining a NetCDF file containing variables such as day (in julian), latitude, longitude, and ozone, I successfully converted the file into a 3D matrix ordered by longitude, latitude, and day. In addition, I possess a .mat file that includes Year, ...

Tips for stopping Angular from rendering a directive that is producing incorrect results after an error is thrown

My directives have a template and a compile function that modifies the template. Occasionally, Angular fails to recognize jQuery (and defaults to using jqLite), causing my compile to encounter errors. Despite this, Angular continues to render the directive ...

adding a new div to the bottom of a row that is being created on the fly

I encountered an issue where rows are created dynamically and I needed to add a div at the end of each row. Despite trying various methods, I faced difficulties as adding the div resulted in extra divs being added to all previous rows whenever a new row wa ...

Tips for toggling the visibility of a flexbox-styled popup using jQuery

I am trying to implement a popup on my website and I want to use flexbox styling for it. I have the necessary scss mixins for flexbox properties, however, I encountered an issue. The problem arises when I try to hide the popup using display: none, as the ...

Node.js's async functions seem to be running sluggishly

My list of queries is all set and ready to go: var array = [ 'UPDATE EVALUATION SET mark = "16" WHERE id_eval = "21" AND id_usr = "125"', 'UPDATE EVALUATION SET mark = "9" WHERE id_eval = "22" AND id_usr = "125"', ...

What is the best way to eliminate words in an array that come after a line break?

I am looking to extract the strings that come after each : and before each \n from this text: När:Sent lördag kväll och natt till söndag\nVar:Främst norra Jämtland\nIntensitet:Väst ca 21 m/s\nKommentar:- Reference source (alert ...

Retrieve information from the index resource using AJAX

I feel like I might be overcomplicating things, but basically, I'm trying to retrieve all the data from an index resource and have it load when a button is clicked using AJAX. I've been using a serializer to tidy up the JSON. Both "/categories" ...

Node server quickly sends a response to an asynchronous client request

Apologies for my lack of writing skills when I first wake up, let me make some revisions. I am utilizing expressjs with passportjs (local strategy) to handle my server and connect-busboy for file uploads. I believe passport will not have a role in this pr ...

The scatterplot dots in d3 do not appear to be displaying

My experience with d3 is limited, and I mostly work with Javascript and jQuery sporadically. I am attempting to build a basic scatterplot with a slider in d3 using jQuery. The goal of the slider is to choose the dataset for plotting. I have a JSON object ...

The retrieval of QJsonArrays from QJsonObject is encountering some issues

Currently, in the project I am working on, I am utilizing Qt's JSON functionality to maintain the state of a graph. In this system, each component recursively calls the toJson functions of its members for serialization. While this process generally wo ...

How can I shrink a PHP array into a significantly smaller JSON file?

I have a PHP array coming from a webservice (soap xml) that I want to filter and convert to JSON (refer to the example below). Check out the sample of the array received from the webservice: (*** indicates the data needed in the final JSON) {"Id":445946 ...

Oops! The page you're looking for at /api/tasks

Whenever I try to access: http://localhost:3000/api/tasks, I keep getting a "Cannot GET /api/tasks" error message. This is my server.js: var express = require('express'); var path = require('path'); var bodyParser = require('body ...

Arrays in Vue Data

After creating an array and pushing data into it, the array turns into a proxy, preventing me from using JavaScript array functions on it. export default { name: 'Home', components: { PokeList, FilterType, SearchPokemon}, data() { r ...

Iterate over the keys and values in a JSON object while simultaneously replacing any specified values in Golang

Is it possible to iterate through all the keys and values of a JSON object in Golang, identify a specific value based on a match with either the key or value, replace that value, and then create a new data structure with the updated value? I came across a ...