Nitish - 1 year ago 81
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) {
numbers.push(randomNumber);
\$scope.randomWord_pair.push(\$scope.word_pair[randomNumber])
}
}
``````

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

How can I fix it?

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.
``````while (\$scope.randomWord_pair.length < displayCount)