Reorganizing Elements within an Array using JavaScript

Imagine I have the characters:

H, M, L

I want to create sorted arrays like this:

var array1 = [ "H", "M", "L", "L", "M", "H" ];

My goal is to avoid having more than one unique character in the first three and last three characters when using the shuffle() function on the array.

For example:

var wrong = [ "H", "M", "M", "H", "M", "L" ]; // note the two M's in the first three values

If I shuffle the array like this:

var array2 = array1.shuffle(); then there might be duplicate characters.

I need help figuring out how to ensure there are no duplicated characters in the first and second sets of three values in the array?

EDIT: Changed random to sorted.

Answer №1

Generate a custom shuffle method, whether within the prototype or as a standalone function

function customShuffle(list) {
  var index = list.length;
  var randomIndex, temp;

  while (index) {
    randomIndex = Math.floor(Math.random() * index);
    index -= 1;
    temp = list[index];
    list[index] = list[randomIndex];
    list[randomIndex] = temp;
  }

  return list;
}


var array = ['X', 'Y', 'Z'],
  result = customShuffle(array.slice()).concat(customShuffle(array.slice()));

console.log(result);

Answer №2

I decided to implement a similar solution based on the guidance provided by @Xotic750.

Array.prototype.shuffle = function() {
  var i = this.length, j, temp;
  if ( i == 0 ) return this;
  while ( --i ) {
     j = Math.floor( Math.random() * ( i + 1 ) );
     temp = this[i];
     this[i] = this[j];
     this[j] = temp;
  }
  return this;
}

var array = [ "H", "M", "L" ];
var b = array.slice().shuffle().concat(array.slice().shuffle());

Check out the JSFiddle for more details.

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

Using jQuery to dynamically add a value to a comment string

Is there a way to dynamically include tomorrow's start and end times in the message for the setupOrderingNotAvailable function if today's end time has passed? The current message states that online ordering will be available again tomorrow from 1 ...

"Unfortunately, the JavaScript external function failed to function properly, but miraculously the inline function

Struggling to create a fullscreen image modal on the web? I was able to get it working fine when embedding the script directly into my HTML file, but as soon as I moved it to an external JS file, things fell apart. I've double-checked all the variable ...

Retrieve a single element from each array stored in MongoDB

Can someone help me with a query in MongoDB? I have a document structure like this, and I am looking to utilize the $addToSet operator to add a value to one of the items within the 'votes' field. However, I also need to remove that value from all ...

JavaScript can be utilized to alter the style of a cursor

I'm currently developing a browser game and incorporating custom cursors into it. To ensure the custom cursor is displayed throughout the entire page, I've applied it in my CSS (though setting it up for 'body' occasionally reverts back ...

The HTML checkbox remains unchanged even after the form is submitted

On a button click, I have a form that shows and hides when the close button is clicked. Inside the form, there is an HTML checkbox. When I check the checkbox, then close the form and reopen it by clicking the button again, the checkbox remains checked, whi ...

MongooseError: The operation `users.findOne()` has encountered an issue

While working on my movie website, I encountered an issue when setting up the login feature. When trying to register using POST through Insomnia, I received an error message stating "MongooseError: Operation users.findOne() buffering timed out after 10000m ...

Make sure to trigger a callback function once the radio button or checkbox is selected using jQuery, JavaScript, or Angular

I'm looking to receive a callback once the click event has finished in the original function. <input type="radio" onchange="changefun()" /> function changefun() { // some code will be done here } on another page $(document).on('input: ...

`There was an issue with an unfinished string literal.`

Currently, I am utilizing jQuery to display the information from a JSON string generated by PHP and extracted from a database. However, I have encountered an issue where some of the data spans multiple lines... How can I prevent this from triggering an un ...

React: Assigning a unique className to an element in a list

In the code snippet below, I am attempting to add a className based on the state of the checkbox. While the className is being added correctly, the issue arises when it gets applied to all elements in the list upon checking/unchecking any checkbox. I aim ...

Saving the author of a message from one function and transferring it to another

I'm currently working on a Discord bot that manages tickets as applications. I've almost completed it, but I want the bot to log the closed ticket when the -close command is used. I've experimented with different approaches, such as using a ...

After completing the purchase, direct the user back to the HomePage

Currently, my development stack involves Reactjs for the UI and Java with Spring Boot for the backend. I have a specific question regarding user redirection after a purchase. For example, how can I direct the user back to the HomePage if they click the b ...

Adding page numbers in a select dropdown menu without using the traditional next and previous buttons

I am attempting to implement a select tag paging feature using the code below: <select ng-change="params.page(page)" ng-model="page" ng-options="page.number as page.number for page in pages"></select> However, I noticed that when I incorporat ...

Instructions on activating dark mode with the darkreader plugin on a Vue.js website

Is there a way to implement DarkMode in a Vue.js application? I attempted to integrate darkmode using this npm package, but I kept encountering the error message: DarkMode not defined. ...

Requirements for using Angular JS and Node JS

With upcoming projects involving AngularJS and Node.js, I'm a bit apprehensive as I don't have much experience with JavaScript. Should I start by picking up a book on each technology, or is it essential to learn more about JavaScript first before ...

Why is it necessary to use process.nextTick() to delay method execution within a PassportJs strategy using Express?

When working with user registration using the passport local strategy, I stumbled upon a code snippet that utilizes process.nextTick to postpone the execution of a method within the Passport LocalStrategy callback. While I grasp the concept of delaying m ...

On startup of the chrome app, read and load a JSON file into a variable

As I develop a chrome app, my goal is to store all configuration defaults in json file(s) alongside other assets. I am currently using AJAX requests to load them, but I'm wondering if there is a more efficient way to handle this. Is there perhaps an o ...

I would greatly appreciate your assistance in deciphering the JavaScript code provided in the book "Ajax in Action"

While reading through the Ajax in Action book, I came across a code snippet that has left me with a couple of questions. As someone who is new to web programming and still getting to grips with JavaScript, I am hoping for some clarity on the following: ...

Generating a preview image for a three.js environment

I am currently working on a website dedicated to visualizing the biological neurons found in animals. I have a comprehensive list of neuron names, and I use THREE JS to draw the neuron when the user clicks on its name. However, with hundreds of neurons to ...

Angular2+ does not return any elements when using .getElementsByClassName() even if they are present

I have a question that seems simple, but I can't seem to find the answer anywhere. I've looked through past questions but still haven't found a solution... In my Angular template, there is a large amount of text inside a div, and some parts ...

Not successfully integrating an angular component

In my Angular application, I am working on creating a new component and injecting it into the app. Below is the code for the angular component: (function(angular) { 'use strict'; angular.module('some.someModule', ['bm.component.t ...