0

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.

Darren Harley
  • 75
  • 1
  • 18

2 Answers2

1

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
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • Many thanks for your reply @Scott Marcus. I tried your answer above, but I got an empty array; `Running: Search using Make ✔ Passed [equal]: 92 == 92 []` – Darren Harley Oct 08 '19 at 11:06
0
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
  • Ok so if I move the `console.log(results)` command, it at least shows that the push is working. Moving it up a line; `results.push(text.value); }); console.log(results); }); });` results in 93 empty arrays. Moving it further up... `results.push(text.value); console.log(results); }); }); });` results in a full, correct array...but there's 93 of them! Any ideas? Thanks – Darren Harley Oct 08 '19 at 14:18