Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

javascript get n random elements from array

// Shuffle array
const shuffled = array.sort(() => 0.5 - Math.random());

// Get sub-array of first n elements after shuffled
let selected = shuffled.slice(0, n);
Comment

javascript get a random array from 1 to n

Array.from(Array(10).keys()).sort(() => 0.5 - Math.random());
//Get Shuffled array from 0 to 10
Comment

get n random items from array javascript

function getRandom(arr, n) {
    var result = new Array(n),
        len = arr.length,
        taken = new Array(len);
    if (n > len)
        throw new RangeError("getRandom: more elements taken than available");
    while (n--) {
        var x = Math.floor(Math.random() * len);
        result[n] = arr[x in taken ? taken[x] : x];
        taken[x] = --len in taken ? taken[len] : len;
    }
    return result;
}
Comment

PREVIOUS NEXT
Code Example
Javascript :: js poll dom 
Javascript :: javascript get child element by class 
Javascript :: javascript rotate image canvas 
Javascript :: how to check if browser tab is active javascript 
Javascript :: bash commands in node 
Javascript :: comment in react 
Javascript :: pdf table files download react not working 
Javascript :: transitionduration 
Javascript :: js get date in ms 
Javascript :: express get raw path 
Javascript :: javascript go to div id 
Javascript :: mysql query node.js 
Javascript :: how create an index mongodb 
Javascript :: destructure dynamic properties 
Javascript :: javascript querySelectorAll id ends with 
Javascript :: javascript date get nearest 15 minutes 
Javascript :: How to create react app with yarn, npx or npm 
Javascript :: javascript convert in a string the items of an array 
Javascript :: convert date to millisecond in javascript 
Javascript :: dynamically add script code to page 
Javascript :: js inline if 
Javascript :: how to check if function is running js 
Javascript :: jquery read query string 
Javascript :: bignumber to number javascript 
Javascript :: javascript count table rows 
Javascript :: prop-types instalation 
Javascript :: javascript subtract 2 dates get difference in minutes 
Javascript :: new File in js 
Javascript :: jsconfig.json 
Javascript :: nodejs mysql connection pool 
ADD CONTENT
Topic
Content
Source link
Name
5+7 =