Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript: Generate random number generated arrays

I am making integration test for my app. I would like to see how cartItems payload my db can write. For that, I have generated cartItems array. Inside that array I have one item called ean. I would like to generate 12 digits random number to ean. But it always return me same number from the array.

I have facing two issue

  1. Could not able generate 12 digits ean number
  2. When I generate the arrays and the 6 digits ean number always same. But I want random numbers

Here is my code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  const requestParameters = {
        id: "530d275e-5de1-466d-86fe-3993a2563fb6",
        cartItems: new Array(500).fill({
          additionalInfo: '',
          brand: '',
          replace: false,
          basicQuantityUnit: 'KPL',
          collectingPriority: 1000,
          ean: Math.floor(100000 + Math.random() * 900000) + 10000, // I want to render random 12 digits
          id: '0200097823340',
          itemCount: '1'
        })
    }
    
    console.log(requestParameters)

>Solution :

You’ve inserted the same item 500 times, but you wanted to create a new one every time. Use map to do this

const requestParameters = {
  id: "530d275e-5de1-466d-86fe-3993a2563fb6",
  cartItems: new Array(5).fill().map(() => ({
    additionalInfo: '',
    brand: '',
    replace: false,
    basicQuantityUnit: 'KPL',
    collectingPriority: 1000,
    ean: Array(12).fill().map(() => Math.floor(Math.random() * 10)).join(''),
    id: '0200097823340',
    itemCount: '1'
  }))
}

console.log(requestParameters)

To generate 12 digits I would use:

Array(12).fill().map(() => Math.floor(Math.random() * 10)).join('')

and if you want it as a number instead of a string use:

+Array(12).fill().map(() => Math.floor(Math.random() * 10)).join('')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading