Home > Net >  How to select radom items in a for loop in jQuery
How to select radom items in a for loop in jQuery

Time:11-19

how to select random items inside a jQuery loop. I have a loop with 30 items where I'm adding some random numbers, now I don't want to add random numbers to all items at once, I would like to add random numbers to random items in the loop.

A good example would be, let's say I want my loop to add 5 to several random items of a loop as shown below

for( var i = 0; i < 30; i    ){
                 if( i 'is in range of radom'  ){
                    i   5;
                 } else {
                    i   0;
                 }
            }

It's like selecting a bunch of items inside a loop, next time selecting another bunch and so on. I can select like 10 random items in a loop to add 5 to, next loop another random 10 items are selected and so on and so forth.

CodePudding user response:

Assuming you mean your 30 items is an array of 30 numbers.

Assuming you want to add a value (in your example, 5) to n random items (in your example, 10 items)

const items = [/* 30 things here */];
for (let i = 0; i < 10; i  ) {
   items[Math.random() * items.length]  = 5;
}

This could possibly add 5 to the same item 10 times, if Math.random() returns similar values.

CodePudding user response:

Consider the following.

function getRandomInt(max) {
  return Math.floor(Math.random() * max);
}

var random = [];

for (var i = 0; i < 5; i  ) {
  random.push(getRandomInt(30));
}

var results = [];

for (var i = 0; i < 30; i  ) {
  if (random.indexOf(i) >= 0) {
    results[i] = i   5;
  } else {
    results[i] = i;
  }
}

console.log(random, results);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Assuming random is an array of "random" entries, you can populate a new array with 30 entries, in order, with salted results.

Results:

[
  0,
  1,
  2,
  3,
  4,
  5,
  11,
  7,
  8,
  14,
  10,
  11,
  12,
  13,
  19,
  15,
  16,
  17,
  18,
  19,
  20,
  21,
  22,
  28,
  24,
  25,
  26,
  32,
  28,
  29
]

You can use .indexOf():

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

If you have an Array of Numbers for example, you can check if a Number is in that array this way.

  • Related