Reputation: 97
Ok, so I have the following code which successfully generates a list (from an element);
this.elements('css selector', '#bfsDesktopFilters .search-filters__item #ddl-make > option', function (result) {
result.value.forEach(element => {
this.elementIdValue(element.ELEMENT, function (text) {
var makeValue = text.value;
console.log(makeValue);
});
});
})`
which results in a (long) list of bike makes, as below;
My question is, how do I randomly select an entry from this list?
I've tried to split the results;
var elementMakesArray = makeValue.split('');
console.log(elementMakesArray);`
but this gave me the following;
I tried this;
var randomMake = Math.floor(Math.random() * makeValue);
console.log(randomMake);`
but got a NaN error.
So I'm just wondering how I can randomly select an entry from the list?
Any help would be greatly appreciated.
Thanks.
Upvotes: 0
Views: 315
Reputation: 134
let result = this.elements('css selector', '#bfsDesktopFilters .search-filters__item #ddl-menter code hereake > option', function (result) {
return result.value.forEach(element => {
return this.elementIdValue(element.ELEMENT, function (text) {
return text.value;
})
})
})
var random = results[Math.floor(Math.random(`enter code here`) * results.length)];
console.log(random); // Log the random string
Upvotes: 0
Reputation: 65806
Your code writes a single string value for each element it finds. What you need to do is take those string values and add them to an array and then you can get a random entry from the array:
let results = []; // <-- This is the array that the results will go into
this.elements('css selector', '#bfsDesktopFilters .search-filters__item #ddl-make > option', function (result) {
result.value.forEach(element => {
this.elementIdValue(element.ELEMENT, function (text) {
results.push(text.value); // Place individual result into array
});
});
console.log(results); // Log the finished array after loop is done
});
// Now that the array is populated with strings, you can get one random one out:
var rand = results[Math.floor(Math.random() * results.length)];
console.log(rand); // Log the random string
Upvotes: 1