Is there a simple method to randomly shuffle a JavaScript array while still maintaining a fixed key?

Let's say I have an array in Javascript:

var my_arr = [1,2,3,4,5,6];

There are numerous methods to shuffle it. Suppose I already have a function called shuffle, like this:

shuffle(my_arr);
// The array could look something like [1,5,4,3,2,6];

However, with each run, the order changes. I am interested in finding out if it's possible to fix the shuffling to a specific value (a number, string, or anything else). The objective is to have the same result every time as long as the key remains unchanged. For example:

var my_arr = [1,2,3,4,5,6];
function shuffle_by_key(arr, key){....}
var new_arr1 = shuffle_by_key(my_arr, 1); 
var new_arr2 = shuffle_by_key(my_arr, 2);
var new_arr3 = shuffle_by_key(my_arr, 1);

The new_arr1 output should match that of new_arr3 since they both share the same key "1".

Answer №1

  1. Create a unique hash function in JavaScript for encoding data
  2. Generate a hash value for the input "salt" to ensure consistency and randomness
  3. Assign shuffling logic based on the values produced by the hash function, using specific digits to manipulate array indices
  4. If needed, re-hash additional times to obtain more digits for shuffling process

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

Adding a string to an array in Unity3D

In my Unity3D 4.2 project, I have a button set up to execute the following function: function SubmitMove() { p1cube = new Array (); p2cube = new Array (); var allCubeList = GameObject.FindGameObjectsWithTag("cube"); for(var allCube: GameObject in ...

An issue occurred while attempting to retrieve an access token in NodeJs, resulting in 500 failures. The error message displayed was: "connect ECONNREFUSED" at process._tickCallback (node

I'm trying to authenticate users using Passport's GoogleStrategy, but I keep encountering the following error. Can anyone assist me? Code passport.use(new GoogleOAuth2Strategy({ clientID : configAuth.googleAuth.clientID, clientS ...

Sending numerous data values, including arrays, via Ajax to PHP

Is it possible to pass multiple variables over to PHP using Jquery/Ajax? I am facing an issue where I can post multiple arrays if all variables are not arrays, but not if some of them are. Here is my code: <script> var mutype; var practiceArray = ...

What is the best way to stop the browser from automatically redirecting to another page after submitting a form?

I am using an AJAX call to a method that returns JSON data. How can I retrieve and read the JSON response without being redirected to a new empty page? [HttpPost] public JsonResult Test() { return Json("JSON return test", JsonRequestBehavior.AllowGe ...

When I log the array in React, I receive an undefined value for the first element even though the array clearly exists

Below is the code snippet I am working with: import React from 'react'; import axios from 'axios' //let termExample = "https://en.wikipedia.org/w/api.php?action=query&origin=*&format=json&generator=search&gsrnamesp ...

Is it possible to use JavaScript to conceal multiple HTML tags simultaneously?

Is there a simple way to toggle HTML elements using Javascript? I have a project with a lot of ascii art and I need a more efficient method to show/hide it without repeating lines of code numerous times. Here's a snippet of the problematic code: ...

Discovering common elements in two multi-dimensional numpy arrays

I recently started learning Python and I've encountered an issue. import numpy as np def find_neighbors(indexset, i,j): temp = np.array([[i-1,j],[i+1,j],[i,j-1],[i,j+1]]) for ele in temp: if ele in indexset: print(ele) ...

Tips for transferring a prop from a parent component to a child in Vue.js

I have a main component named Stepper that includes a child component called ShortSummary. I am attempting to pass a property from Stepper to ShortSummary by clicking on a radiobutton, but it is not working! Here's my setup. This is the code for Stepp ...

Retrieve all elements from a "line" within a given array using PHP

Is there a way to calculate the total sum of values in a specific "row" within an array? Consider this sample array: [0] {array( "date" => "2015-01-01", "value" => 5) } [1] {array( "date" => "2015-01-02", "value" => -3) } ... I'm intere ...

Angular ng-bind-html directive allows you to bind HTML content to an

I am attempting to utilize $interpolate and ng-bind-html in order to bind the data from my scope variable to an html string as outlined in this solution. However, I have encountered an issue where the ng-bind-html result does not update when the value of m ...

Leap over in a similar fashion to the provided demonstration

In my attempt to create a unique project, I have created this CodePen example. The goal is to have one ball on the circle that remains in a fixed position, while another rotating main ball must avoid touching it at all costs. Points are awarded for success ...

What is the method for assigning a string to module variable definitions?

As someone new to TypeScript and MVC, I find myself unsure if I am even asking the right questions. I have multiple TypeScript files with identical functionality that are used across various search screens. My goal is to consolidate these into a single fil ...

Creating a forEach statement in an express.js router to handle JSON data

I need help creating an API that will generate a JSON output containing the names extracted from the forEach loop. There are 8 names being processed and I can only use res.send once. See the code snippet below: timeSeries.forEach(data => { res.js ...

Angular input field for IP addresses with a mask applied

Incorporating angular/ui-mask into my current project has been helpful, but now I am looking for a way to mask IP address ranges (ex. 192.168.70.18/20). Here is what I have so far: <input ng-model="address" ui-mask="9?9?9.9?9?9.9?9?9.9?9?9/9?9" ui-ma ...

Guide to displaying numerous points on mapbox by utilizing a for each loop statement

I have a 2D array containing longitudes and latitudes that I need to map using MapBox. The example I found only demonstrates plotting two points, so I attempted to use a for-each loop to iterate through my 2D array and plot all the points. However, I enco ...

Restore original state on various elements using JavaScript

I recently asked a question about changing the height of images when clicking on them using vanilla JS. A helpful user named Butalin provided me with a working function, but there seems to be an issue - if I click on one image to change its height and then ...

tips for building angularjs widgets with limited scope

Is there a way to generate widgets from HTML scripts on a webpage? For example: <script type="text/html" id="widget-simple"> <div class="widget-simple"> This is my widget and its name is {{ test }} </div> </script> & ...

Instructions for creating a directional route on a map using highcharts

I am currently working on implementing highcharts maps with flight routes, similar to the visualization shown in this Highchart-maps with flight routes example. My goal is to display the routes in a way that resembles the output illustrated in this expecte ...

Using inline SVG in a Vite production build

When utilizing Vite and Vue, my goal is to compile a single JavaScript file without creating an assets directory that includes SVG and GIF files during the build process. I want to achieve this without manually inserting the SVG code in a Vue JS file as a ...

Loop through associative array in PHP using JQuery

I have a PHP associative array and I am using JQuery AJAX to retrieve the result array. My issue arises when passing the result to jQuery and attempting to loop through and extract each Sequence, Percent, and Date. I need to store this extracted data in a ...