Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
How to select radom items in a for loop in jQuery

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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);

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!