Darren Harley
Darren Harley

Reputation: 97

Select random entry from string list in javascript

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;

enter image description here etc, etc

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;

enter image description here

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

Answers (2)

Muhammad Junaid Aziz
Muhammad Junaid Aziz

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

Scott Marcus
Scott Marcus

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

Related Questions