Nitish Nitish - 9 months ago 35
Javascript Question

Javascript for loop for exact iterations

I have a for loop to push a random number of unique elements from a big array into another small array. I want exact number of elements to be pushed into that small array.

$scope.word_pair = [
{'word':'Carla', 'pair':'Lion'},
{'word':'Sophie', 'pair':'Lotta'},
{'word':'Jannes', 'pair':'Stubbi'},
{'word':'Martin', 'pair':'Wolle'},
{'word':'Flo', 'pair':'Ign'},
{'word':'Rere', 'pair':'Rose'},
{'word':'Jean', 'pair':'Tamara'},
{'word':'Memo', 'pair':'Elk'},
{'word':'Nila', 'pair':'Naph'}

/* To select limited random items to display */
var displayCount = 3 //count should change at each level
$scope.randomWord_pair = []
var numbers = [];
for (var i = 0; i <= displayCount; i++) {
var randomNumber = Math.floor(Math.random() * 4);
if (numbers.indexOf(randomNumber) == -1) {

decides how many (exact) number of elements I want in my
array. However, sometimes it gives me other than 3 elements in

How can I fix it?


There are two reasons for that:

  1. You're looping too much. i = 0; i <= displayCount; i++ will give you four iterations for displayCount = 3, not three: i will be 0, then 1, then 2, and then 3.

  2. You're not looping enough. :-) You're only pushing a number if you don't find it, meaning you don't always push a number for a loop iteration.

Just use

while ($scope.randomWord_pair.length < displayCount)