I have a function, getUnusedName
that returns a random name, but first checks if it's already used by any object within a second array.
Observing how many times the function is called across multiple runs shows a pretty wide variation as I would expect when using random. Is there a more efficient way of achieving this?
As well as a general code review, I'd also like to ask:
If possible, I'd like to avoid removing items from
names
, which is why I have chosen the random solution. Is this a bad choice? What are my alternatives?Is there a cleaner way to check if a name is already in use? Using
Array.filter
then checking the resulting length seems a little verbose.
var names = ['Steve', 'Adam', 'Phillip', 'Thomas', 'John', 'Joseph'];
var people = [];
var calls = 0;
function getUnusedName() {
calls++;
var randomName = names[Math.floor(Math.random() * names.length)];
if (people.filter(function (val) { return val.name === randomName; }).length === 0) {
return randomName
} else {
return getUnusedName();
}
}
for (var i = 0; i < names.length; i++) {
var name = getUnusedName();
people.push({
name: name,
age: (i * i) + 20,
});
}
console.log('getUnusedName calls: ' + calls);
console.log(people);
names
array, and then just taking one name at a time? Would that be a solution? Or should thenames
not be altered at all? \$\endgroup\$