Is it possible to shuffle an array to a specific size in JavaScript?

Let's consider an array:

array1 = [1, 2, 3, 4, 5, ........, 50]

If we want to create a new array by randomly selecting elements from array1 with a specific length constraint, for example 5 numbers, the result could be:

var arrayLength = 5

randomizedArray = [6, 20, 45, 2, 13]

Is it possible to achieve this using Math.random?

Answer №1

To generate a random array, you can iterate over each item in the array and assign a value that is the result of multiplying Math.random() by the upper bound (after rounding it off):

function createRandomArray(size, limit){
  return new Array(size).fill().map(element => Math.round(Math.random() * limit))
}
console.log(createRandomArray(5, 10));

Answer №2

When dealing with a reasonable range (0..60), I would opt for shuffling and slicing. It's always handy to have an array shuffle function available as it can be a versatile tool in many scenarios.

// Source: https://stackoverflow.com/a/2450976/294949
function customShuffle(array) {
  let currentIndex = array.length,  randomIndex;
  while (0 !== currentIndex) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;
    [array[currentIndex], array[randomIndex]] = [
      array[randomIndex], array[currentIndex]];
  }
  return array;
}

let range = 60;
let resultLength = 5;
let originalArray = [ ...Array(range).keys() ]; // Original array

customShuffle(originalArray);
console.log(originalArray.slice(0, resultLength))

Answer №3

One way to iterate 5 times through the array and randomly push an index is by utilizing the Math.random() function in JavaScript:

let array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50];

let newLength = 5,
    newArray = [];

for (let i = 0; i < 5; i ++) {
  newArray.push(array1[Math.floor(Math.random()  * (array1.length - 1))]);
}

console.log(newArray);

It's important to note that this approach may result in duplicate items being pushed into the new array. To avoid this, you can use the includes() method to check if an element was already included before pushing it:

let array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50];

let newLength = 5,
  newArray = [];

for (let i = 0; i < 5; i++) {
  let randomElem = null;
  // Check if element is already in the array
  do {
    randomElem = array1[Math.floor(Math.random() * (array1.length - 1))];
  }while(newArray.includes(randomElem));
  
  newArray.push(randomElem);
}

console.log(newArray);

Answer №4

While others have already discussed the traditional approach, I want to highlight that rando.js is a great tool for handling this type of task.

//In case you need to work with an array
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50];
console.log(randoSequence(arr).map(a => a.value).slice(-5));

//Alternatively, if you prefer a simpler approach
console.log(randoSequence(1, 50).slice(-5))
<script src="https://randojs.com/2.0.0.js"></script>

Answer №5

In this scenario, rather than inserting n values, it is recommended to insert n distinct values if the requirement demands it. This precaution should be taken especially when n approaches the length of the array, as there is a risk of elements being repeated.

Below is a straightforward code snippet that does not require importing any new node_modules:

let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50];
let newArrayLength = 10;
let newArray = [];

while (newArrayLength > 0) {
  const rndIndex = Math.floor(Math.random() * array.length);
  if (!newArray.includes(array[rndIndex])) {
  newArray.push(array[rndIndex]);
  newArrayLength--;
  }
}
console.log('newArray', newArray);

Answer №6

Method 1: Randomize the array and select first N items

An option is to randomize the entire array and then pick the initial 5 elements. While this approach may consume more time and memory, it becomes noticeable mainly with large inputs or where performance matters significantly.

Utilize any conventional technique for shuffling an array:

function shuffle(array) {
    return array.map((value) => ({ value, sort: Math.random() }))
        .sort((a, b) => a.sort - b.sort)
        .map(({ value }) => value)
}

Then:

const arrayLength = 5;
const array1 = [1, 2, ..., 50];

const shuffled = shuffle(array1);
// extract the first n elements from the shuffled array
const sample = shuffled.slice(0, arrayLength);

Method 2: Employ a pre-existing library

Several libraries already have functionality similar to the one you seek - specifically obtaining a random selection of N elements. For instance, consider using lodash's sampleSize as mentioned in this response.

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

Ensure the most recently expanded item appears at the top of the TreeView by updating to Mui version

I'm working on a feature where I want to scroll the expanded TreeItem to the top when it has children and is clicked on for expansion. Any suggestions on how to make this happen? ...

React component fails to run within a foreach iteration

function displayCourses(props) { props.courses.forEach(course => { return <Header name={course.name} />; }); ... } The provided code is not properly rendering the Header component. By modifying the loop to course => console.log(cours ...

What is the best way to duplicate a set of objects in ThreeJS?

I am trying to develop an educational activity for my students wherein a group of objects needs to be replicated and positioned randomly in a scene. I have created a function for this purpose, but unfortunately, it only duplicates the same object instead o ...

Sharing Data via JSON for a Pop-Up Display

section of a website, there is a button that, when clicked, triggers a small pop-up. The data being posted appears to be in JSON format as seen in HttpFox. Personally, I have little knowledge of javascript and AJAX. When the specific button is clicked, i ...

Ember: Trigger a Function on Input Field Blur with Parameter

Currently, I am in the process of developing a basic Todo App to get familiar with EmberJS version 2.14. One feature I aim to integrate is manual inline editing where users can double-click on a todo item text span to activate an input field for editing. T ...

React state change does not effectively adjust Grid Size

I am facing an issue with adjusting the grid size in my Conway game of life app. Whenever I click on the buttons to change the numCols or numRows, only one of them gets updated in the app. How can I effectively update the state so that the grid changes siz ...

The code is slicing data, but the changes are not reflecting in the user interface

Initially, there are three drop down menus displayed. Upon selecting an option from the first drop down menu, the values in the second drop down menu load. After selecting an option from the second drop down menu, a new set of drop downs appears. However, ...

Tips for preserving the current DOM using Ajax, jQuery, and PhP

I made some changes to my page by adding new divs, and now I want to save all of it, replacing the old content. Example of the DOM body: <body> <div id="save_dom">Save</div> <div class="box">111</div> <div cla ...

Retrieve the total count of tables within a specific div element

If I have an unspecified amount of tables within a div, how can I determine the total number of tables using either plain JavaScript or jQuery? ...

Difficulty encountered when populating an array with a dynamic class template

Rules: The implementation cannot use the STL for managing dynamic arrays. I've hit a roadblock with this problem and my attempts to find a solution have come up empty so far. Any assistance would be greatly appreciated! My goal is to create a progra ...

Unable to retrieve responseText from AJAX call using XrayWrapper

I am utilizing the IUI framework and attempting to retrieve the results from an ajax call. When inspecting the call in Firebug, it shows an "XrayWrapper[Object XMLHttpRequest{}", but I am struggling to access the responseText from the object. Upon expand ...

Warning: Fastclick alerting about an ignored touchstart cancellation

Having an issue with a double popup situation where the second popup contains selectable fields. Below is the code snippet I am using to display the second popup: $("#select1").click(function(e) { e.stopPropagation(); var tmplData = { string:[& ...

Create a polling feature using a Grease Monkey script

I am looking for a way to run a Tamper Monkey script on a Facebook page that regularly checks a database for new data and performs certain actions. I have attempted to implement polling using AJAX, and below is the code I used: (function poll() { setT ...

The react-bootstrap implementation is not functioning as expected, resulting in an unsupported server component error

Having an issue with an Unsupported Server Component Error while using react-bootstrap with typescript. I've shared the contents of my page.tsx file, layout.tsx file, and the specific error message. layout.tsx file import type { Metadata } from &apos ...

The HTML view is unable to display the CSS style due to a MIME-type error

I have recently developed a very simple Express app that is supposed to display a single view called home.html from the view directory. Although the home.html file is being shown, none of the CSS styles I added seem to be loading. The console is throwing t ...

What is the process for testing promise functions that contain an internal promise using Jasmine in an Angular environment?

In my service function, here's how it looks: asyncGetStuff: (id) -> stuff = [] @asyncGetItem id .then (item) -> #parse some data stuff.push data return stuff Now I am trying to verify the contents of 'stuff': ...

Adjust the size of the scene to make it smaller and position the canvas within a div

My current project involves Three.js and can be accessed here in its entirety. The particles in the project have a lot of vertical space around them that is unoccupied. I am trying to find a way to reduce this space or put the project inside a div. I trie ...

A step-by-step guide on sending a fetch request to TinyURL

I have been attempting to send a post request using fetch to tinyURL in order to shorten a URL that is generated on my website. The following code shows how I am currently writing the script, however, it seems like it's not returning the shortened URL ...

"Converting circular structure into JSON" - Inserting BigQuery Data using Cloud Function in Node.js

I am currently facing an issue while attempting to load an array of JSON objects into a BigQuery Table from a Cloud Function built in NodeJS. Despite not having any circular references, I encountered the error message "Converting circular structure to JSON ...

Tracking the progress of an AJAX call with a progress bar or progress status

Using an ajax call, I want to display progress status inside a text box. Below is the code for the ajax call: <input type="text" name="cm" id="cm" /> <script type="text/javascript" language="javascript"> $('#cm').blur(function() ...