Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

js how to get random number (inclusive min max) and push it in an array

const MIN = 1000
const MAX = 9999

const myNumbers = [ 2355, 7235, 8135, 1762, 2361, 8351 ]

/* -------------------------------------------------------------------------- */

/**
 * Returns a random number, including the maximum and minimum.
 * @param {number} min
 * @param {number} max
 * @returns {number}
 */

const randomInRange = ( min, max ) => {
  const randomNumber = Math.floor( Math.random() * ( max - min + 1 ) + min )
  return randomNumber
}

/* -------------------------------------------------------------------------- */

/**
 *
 * @param {number} min
 * @param {number} max
 * @param {number[]} arr
 * @returns {number[]}
 */
const addRandomNumberToArray = ( min, max, arr ) => {
  /**
   * @type {number}
   */
  let randomNumber
  const updatedArray = [ ...arr ]
  // const updatedArray = arr.concat( [] )

  do {
    randomNumber = randomInRange( min, max )
  } while ( arr.includes( randomNumber ) )

  updatedArray.push( randomNumber )

  return updatedArray
}

const updatedArray = addRandomNumberToArray( MIN, MAX, myNumbers )

console.log( 'ORIGINAL ARRAY', myNumbers )
console.log( 'UPDATED ARRAY', updatedArray )
Comment

PREVIOUS NEXT
Code Example
Javascript :: Calculator for two numbers 
Javascript :: detect sound chrome extension every 1 second 
Javascript :: Function Written In Constructor Involving A Promise, Can Be Accessed As Below 
Javascript :: save to text or html file very good 
Javascript :: call the httpclient.get method called 
Javascript :: Toggle child element onclick of parent element 
Javascript :: useDapp connect metamask example 
Javascript :: how to get mempool transactions and decode with ethers js 
Javascript :: prisma bytes 
Javascript :: magnetic button vanilla js 
Javascript :: Jquery works only on double click 
Javascript :: get images from mysql with php jquery ajax and display them in html page inside DIVs 
Javascript :: Backbone View Event 
Javascript :: react : calling APIs after render w error message 
Javascript :: supabase 
Javascript :: How many options are there to climb a ladder with N 
Javascript :: Backbone Model+Collection Minimal 
Javascript :: filter function in javascript 
Javascript :: password generator and password strength using javascript 
Javascript :: regexp object 
Javascript :: electron js execute command line 
Javascript :: math.ceil node js 
Javascript :: regex javscript 
Javascript :: animation js 
Javascript :: search query in javascript 
Javascript :: react native app exit 
Javascript :: javascript variable hoisting 
Javascript :: javascript Skip Items 
Javascript :: javascript function invocation 
Javascript :: nodejs: Basic: managing file: Read, Write, Create, Delete 
ADD CONTENT
Topic
Content
Source link
Name
9+6 =