简体   繁体   中英

Select random object from array and decrement value

I want to know how can I randomly select an object from an array and decrement the value of valid .

I have the following:

const codes = [
   {
      code: "AG1",
      valid: 20
   },
   {
      code: "AG2",
      valid: 20
   },
   {
      code: "AG3",
      valid: 20
   }
]

Now I select the object random like this

var code = codes[Math.floor(Math.random()*codes.length)];

After I select an object I need to decrement the object's value of valid by one

Any idea?

You can use -- to decrement

 var codes = [{ code: "AG1", valid: 20 }, { code: "AG2", valid: 20 }, { code: "AG3", valid: 20 } ] var rand=Math.floor(Math.random() * codes.length); console.log(codes[rand].valid!=0?--codes[rand].valid:codes[rand].valid); 

If you need to keep the changes on the array you can just use codes[idx].valid-- after you got the random index :

 const codes = [ {code: "AG1", valid: 20}, {code: "AG2", valid: 20}, {code: "AG3", valid: 20} ]; const decRandom = (codes) => { let idx = Math.floor(Math.random() * codes.length); // Decrement only if greater then zero. codes[idx].valid > 0 && codes[idx].valid--; } let iteration = 0; setInterval(() => { decRandom(codes); console.log("Iteration: " + ++iteration, JSON.stringify(codes)); }, 2000); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM