What is the best way to select a color at random from an array without any duplicates?

When iterating through a group of 15 users to create a table row for each user, I am interested in randomly choosing a color from my theme's array of 4 colors for each user. How can I efficiently ensure that no two identical colors are next to each other?

Furthermore, is there a way to generate the colors in a way that appears as random as possible on a larger scale? I want to avoid a pattern where it looks like I am simply cycling through the 4 colors in order, resulting in the same sequence every 4 users.

Answer №1

A different way to phrase the question would be:

What is the method to select a random index in an Array that is different from the previously selected index?

The solution involves keeping track of the previous index and selecting a new one until it is different. Here is a general solution to achieve this:

function randomOver(arr) {
  let last = 0 
  return () => {
    let i = last
    while (i == last) i = Math.floor(Math.random() * arr.length)
    return last = i
  }
}

const colors = ['pink', 'violet', 'coral', 'khaki'],
      getIndex = randomOver(colors),
      list = document.getElementById('list')
for (let i = 0; i < 15; i++) {
  const e = document.createElement('tr'),
        x = getIndex()
  e.textContent = 'user' + i 
  e.style.backgroundColor = colors[x]
  list.appendChild(e)
}
<table id='list'></table>

This method ensures a high level of randomness. However, does it result in a visually appealing outcome? The answer to that question is not entirely clear.

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

When using mongoose, is it possible to add a new item and retrieve the updated array in one endpoint?

My API endpoint for the post operation query using mongoose is not returning the updated array after adding a new item. I have been struggling with this issue for 3 days without any success. Any help would be greatly appreciated. router.post("/:spot ...

Which HTML element does each script correspond to?

Are there any methods to identify the script used in certain HTML elements? For instance, if I wish to determine the script responsible for creating a drop-down menu, I can locate the HTML and CSS for the menu but not the JavaScript (or other scripts). I ...

Utilizing various camera set-ups within Three.js

How can I smoothly switch between two different cameras in Three.js while transitioning from one to the other? Imagine a scene with a rock and a tree, each having its own dedicated camera setup. I'm looking for a way to seamlessly transition between ...

What is the best way to merge angularjs modules?

In my angularjs application using the codeigniter PHP framework, I have implemented 3 modules - cars.js for car details, cellphones.js for cellphone details, and home.js for home details. Each module caters to a different client's needs. I am trying ...

Implementing a string replacement within an array of objects using TypeScript

I have a collection of array objects displayed below [ { "subjectID": 1 "Chosen" : "{subjectsChosen:Python,java,Angular}" "password": "{studentpw:123456abcd}" }, { "subjectID": 2 ...

Tips for adjusting the height of a Safari extension during runtime

After successfully developing a Safari extension, I am facing an issue with adjusting the width and height of the popover dynamically at runtime. Can anyone provide insights on how to modify the dimensions of the popover based on its content? ...

The Lua UI text contains numerous strings, each with the presence of the word "or"

As a newcomer to Lua, I could really use some assistance with this script. It involves checking text on the player UI and works fine when it equals a specific value like game:GetService("Players").LocalPlayer.PlayerGui.Main.Border.ClassLabel.Te ...

There seems to be an issue with Material UI Autocomplete not responding to the onChange value

I am currently developing a project using reactjs and incorporating material ui to create components. One specific component I have utilized is the Autocomplete within a form for event creation in my project. I am encountering an issue where I want the sta ...

Is it possible to transform a ReadonlyArray<any> into a standard mutable array []?

At times, when working with Angular functions and callbacks, they may return a ReadonlyArray. However, I prefer using arrays in the traditional way and don't want to use immutable structures like those in Redux. So, what is the best way to convert a ...

Error: Invalid argument provided for foreach() function when attempting to iterate over an array containing JSON objects

While working on decoding an array of JSON objects into HTML lists, I encountered an error. The error message indicates: "Invalid argument supplied for foreach(). What could be missing in my code?" <?php $json_string = '{"error":false,"data":[{"jb ...

Ways to disable mousewheel function in jQuery

I am trying to deactivate the mouse scroll in jQuery and successfully did so, however, I encountered this error message jquery.min.js:2 [Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See Thi ...

How can I stop an element from losing focus?

One issue I'm facing is that when I have multiple elements with the tabindex attribute, they lose focus when I click on any area outside of them. The Problem - In traditional desktop applications, if an element is not able to receive focus, clicking ...

Exploring the world of Node.JS and AngularJS through the integration of API routes

Currently, my backend is built using Node.JS with Express and serving as my API servlet. On the frontend, I'm utilizing AngularJS for the user interface. After numerous searches on Google, I was able to resolve an issue where I faced challenges using ...

Monitoring user engagement using Socket.io and Firebase

In my Node/Express app, I am working on monitoring active users without using sessions. The app relies on an external API for handling JWT tokens that are directly passed to the client for storing and subsequent API requests. To track active users, I am u ...

When using Angularjs and UIRouter, calling event.preventDefault() will prevent the default browser behavior and

A custom JavaScript prompt is triggered when a user clicks the back button on their browser by monitoring the $stateChangeStart event. Let's explore this scenario: Imagine users moving through pages 1, 2, and finally reaching page 3. Upon trying to g ...

Utilizing node.js with restify to manage an array parameter

My node.js server is using restify, and I am trying to send it a get request containing an array of names. This is the format I believe the request should follow: /users?names=bob,joe,michael,joey Can someone confirm if this query is correct? Additional ...

Using Node.js to Send Emails via API

I've been grappling with an issue for over a week while trying to develop a web application that sends welcome emails to new subscribers. Despite my API code working perfectly, I cannot seem to get any output on the console indicating success or failu ...

Is the vertex count of a Geometry in Three.js increased when it is converted to a BufferGeometry?

Recently, I've been experimenting with the fromGeometry method to convert regular Geometry objects into BufferGeometry objects. To my surprise, I noticed that the number of vertices increases during this conversion process. For instance, consider the ...

Injecting Vibrant Lines into Browser Using three.js

My current project involves drawing colored lines in a browser without using meshes. I am retrieving data from a MySQL database where geometry and other attributes are stored, and then converting this data into text blocks that create individual line objec ...

Tips for transmitting a batch of resources with Restangular?

Suppose I need to make a DELETE request to delete multiple products from the resource /products. The complete request should be sent to this URI: /products/ids=1&ids=2&ids=3 What is the method to send a request like this using Restangular? The c ...