Home > Enterprise >  replace some numbers in array
replace some numbers in array

Time:10-05

Hi i recently did a number generator and i have an array filled with 0, 0, 0, 0, 0, because it generates numbers from 0 - 99999 and i want to make it replace only a few elements, for example if it generates 123 then i want an array to be [0, 0, 1, 2, 3], if 4467 then [0, 4, 4, 6, 7] etc any suggestions? thats the code i have for array:

let randInt = Math.floor(Math.random() * 100000);
let separated = [0, 0, 0, 0, 0];

separated = Array.from(String(randInt), Number);

CodePudding user response:

Here's how you do it

  • convert the number to a string
  • pad the string with leading "0" so it is 5 characters long
  • split
  • map to Number
  • profit

OK, the last step is optional :D

// set to 123 to demonstrate
const randInt = 123;// Math.floor(Math.random() * 100000);
const separated = randInt.toString().padStart(5, 0).split('').map(Number);
console.log('Output:', separated);

Another alternative

  • add 100000 to the random number, therefore you get numbers 100000-199999
  • toString
  • split('')
  • slice(1) (to remove the leading 1)
  • map to Number

note: the split('').slice(1) can also be slice(1).split('')

So really, that's two more solutions :p

const randInt = Math.floor(Math.random() * 100000   100000);
const separated = randInt.toString().split('').slice(1).map(Number);
console.log(randInt, separated);

CodePudding user response:

If you want to use a full string, you can use padStart to add in leading zeros. You can split it and map it to the new array.

const separated = Math.floor(Math.random() * 100000).toString().padStart(5, '0').split('').map(Number);

console.log(separated);

You can also just do it from Array.from

const nums = Array.from( {length: 5}, () => Math.floor(Math.random()*10));

console.log(nums);

CodePudding user response:

Hope it'll be helpful.

 const randomNum = Math.floor(Math.random() * 100000); 
 console.log('randomNum is '   randomNum);
 let finalResult = [0,0,0,0,0];
    let result = randomNum.toString().split('');
    result = result.map(num=>parseInt(num));
    const gap = finalResult.length - result.length; 
    if(gap>0){
      for(let i = 0; i< finalResult.length - gap; i  ){
        finalResult[i gap] = result[i];
      }
    }
    else
      finalResult = result;
    console.log(finalResult);

CodePudding user response:

Leveraging lodash utility padStart and includes logic for variable size max:

import { padStart } from 'lodash';

const MAX = 1000;

let randInt = Math.floor(Math.random() * MAX);
const padTo = MAX.toString().length - 1

const paddedNumArr = (padStart(randInt.toString(), padTo, '0'))
      .split('')
      .map(i => parseInt(i));

  • Related