Looking for a method to have two elements select random items from an array without selecting the same item in JavaScript?

I've recently developed a function that allows two different elements (randomColor1 and randomColor2) to select colors from an array. However, the issue arises occasionally where both elements end up picking the same color.

The value of both elements ends up being identical.

Below are my codes. Can someone guide me on how to modify them in order to ensure that both elements choose distinct colors each time? I am still learning JavaScript.

function GetValue() {
  var myarray = new Array(" #ff0000 ", " #ffe100 ", " #95ff00 ", " #2c8d94 "," #911961 ");

  var randomColor1 = myarray[Math.floor(Math.random() * myarray.length)];
  var randomColor2 = myarray[Math.floor(Math.random() * myarray.length)];
  
  document.getElementById(" message ").innerHTML = randomColor1 + randomColor2;
}

Answer №1

To prevent selecting the same element from the array twice, simply remove the selected item after picking it:

let chosenItem1 = myarray.splice(Math.floor(Math.random() * myarray.length), 1)[0];
let chosenItem2 = myarray.splice(Math.floor(Math.random() * myarray.length), 1)[0];

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

I am looking to deactivate the Log-in time button

I am looking to implement a functionality where the Login time button is disabled, but when the Logout time button is clicked, I want to enable the login button again. However, if the page is refreshed and the user has already printed their login time, I d ...

Creating a Typescript type for the react-intl component within a single file

Currently, I'm trying to incorporate the injectIntl component directly in the file instead of using the traditional export default injectIntl(Component). However, I am encountering difficulties when it comes to typing the component. This is a snippet ...

Incorporate HTML into a webpage using JavaScript along with variables

So, I need to dynamically add and remove content to an HTML page with complex styling and data sets that will change based on the clicked element. An example scenario could be like this... <li class="foo"> <div class="slider" data-one="foo" d ...

What is the best way to prioritize List Items over menu items in the front?

Sorry if the title is unclear, let me clarify with some images. First, here is how the navigation bar looks in full window view: Now, this is what happens when I decrease the screen resolution: The items list seems to be hiding behind the menu items. Ho ...

Is it feasible to have a full screen display using CSS?

Is it achievable to achieve a full-screen display like the one seen when using the F11 key on certain flash websites? If so, would anyone be able to provide guidance or code in CSS for this feature? Thank you. For example: ...

An array containing numerous "case" triggers

var message = "hello [[xxx]] bye [[ZZZ]]" var result, re = /\[\[(.*?)\]\]/g; while ((result = re.exec(message)) != null) { switch (result[1].toLowerCase()) { case "xxx": console.log("found xxx"); br ...

How can I locate the template path in an Angular directive?

I've recently developed a directive for my Angular app, using templateUrl to access the template. Everything worked smoothly on my local server, but upon hosting it on Firebase, an error message kept popping up - WARNING: Tried to load angular more ...

Having issues with passing a variable in a JQuery post request

Trying to send the src of an image to a Django view upon clicking a button. Here's what my template looks like: $("#url_submit").click(function() { var film = "{{ filmname }}" var id = {{ id }} $.ajax({ url: "/db/gallery2/" + film + "/" ...

Is there a way to use JavaScript to change the text displayed in this ASPX control?

On an ASPX page, I have the following input control: <input tabindex="0" class="_f_ql _f_rl textbox allowTextSelection placeholderText" role="textbox" aria-labelledby="MailCompose.SubjectWellLabel" autoid="_f_B2"></input> I am limited to inje ...

Executing a function in AngularJS using PHP

My current project involves an Angular application that needs to load a PHP page within the view. The setup is functioning properly, but I now require an Angular function to run after the PHP code has loaded. I am wondering about the process of calling an ...

Check if an element possesses a specific property and corresponding value in JavaScript

I was looking to determine if an object has a specific property with a certain value, and wanted to search for it within an array of objects. var test = [{name : "joey", age: 15}, {name: "hell", age: 12}] After testing the code snippet below, I realized ...

Error message when using Vue Global Filter: Value undefined is not defined

Trying to format currency, I initially attempted to use a global filter in Vue: Vue.filter('formatMoney', (val) => { if (!value) return '' val = val.toString() return val.replace(/\B(?=(\d{3})+(?!\d))/g, ",") ...

What is the best way to simulate an external class using jest?

My Vue page code looks like this: <template> // Button that triggers the submit method </template> <script> import { moveTo } from '@/lib/utils'; export default { components: { }, data() { }, methods: { async ...

Exploring the use of properties in JavaScript

I recently began learning Vue.js 2, but I encountered an issue when passing props to a child component. Here's the code snippet where I pass the prop: <div class="user"> <h3>{{ user.name }}</h3> <depenses :user-id="user.id"&g ...

Different types require individual declarations for their private properties

While immersing myself in learning Angular, a TypeScript-based framework, I encountered an intriguing error: The class 'SnackbarService' is mistakenly extending the base class 'MatSnackBar'. There are separate declarations for types of ...

Misplaced shadow map making unexpected appearance

I am currently utilizing the shadow map plugin in three.js and have encountered some challenges along the way. Despite getting an acceptable image, I am still facing a final issue - shadows appearing on top of some surfaces with normal 0,0,1. Attached belo ...

Adjusting the Size of Images in WooCommerce

Whenever I visit the Shop Page, or use the following shortcode: [featured_products per_page="4" columns="4" orderby="date" order="ASC"] or this one: [best_selling_products per_page="4" columns="4"] I notice that the images displayed are in different si ...

JavaScript program that continuously reads and retrieves the most recent data from a dynamically updating JSON file at regular intervals of every few seconds

I am a beginner in JavaScript and I'm facing an issue with displaying the most recent values from a .json file on an HTML page. The file is updated every 10 seconds, and I am also reading it every 10 seconds, but I'm not getting the latest data. ...

Updating the text input value in a database with PHP upon button click

Here is a breakdown of what has been implemented so far: The database table is named adhar_card. Below is the structure image for reference (Adhard_card_id serves as the primary key). https://i.sstatic.net/8j4m6.jpg Clicking on the verify button will cha ...

Can you point me to the location where the 'req' parameter is specified?

I've been exploring a new authentication approach detailed in this article. One issue I'm encountering is locating where the req parameter is declared in the snippet below. It seems like my code won't compile because this parameter isn&apos ...