Reputation: 14492
I want to create a function that generates random Integers from a certain interval and each time it is called, it should produce a unique one. For that I have created this generateUniqueInt
.
function generateUniqueInt() {
var res = Math.floor(Math.random() * 100);
while (generateUniqueInt.used.indexOf(res) !== -1)
res = Math.floor(Math.random() * 100);
generateUniqueInt.used.push(res);
return res;
}
generateUniqueInt.used = new Array;
for (let i = 0; i < 20; i++) {
console.log(generateUniqueInt());
}
generateUniqueInt.used.sort();
console.log(generateUniqueInt.used);
I called this function few times like this and it works.
Then I wanted to check which values were actually generated and for easier inspection I sorted the used
property. But as it seems, used
is not an array anymore.
I have tried using generateUniqueInt.used = [];
as well as Object.defineProperty
but the outcome is the same each time. What am I missing here? Is there a way to create used
as an array?
Upvotes: 2
Views: 107
Reputation: 5473
Your issue is :The default sort order is according to string Unicode code points.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
So below code will return following output:
var array1 = [1, 30, 4, 21];
array1.sort();
console.log(array1);
// expected output: Array [1, 21, 30, 4]
In order to solve for numbers you will may follow example from MDN:
var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
return a - b;
});
console.log(numbers);
// [1, 2, 3, 4, 5]
So your example would become following which should give you correct desired output:
generateUniqueInt.used.sort(function(a,b){ return a - b});
Upvotes: 2
Reputation: 17654
By default the sort method sorts elements alphabetically, so your array will be sorted like [1,2,25,3,4 ...]
use this to sort an array of numbers :
generateUniqueInt.used.sort(function(a,b){ return a - b});
let arr = [4,2,65,12,23,5,3]
let sorted1 = arr.sort()
console.log('sorted alphabetically : ', JSON.stringify(sorted1))
let sorted2 = arr.sort(function(a,b){ return a - b})
console.log('sorted numerically : ', JSON.stringify(sorted2))
Upvotes: 2