I am trying to generate a random SKU number from the array. Using Math.floor() and Math.random() to get the index. But it only returns a letter or number instead of the entire string. Here is the function:
function bookRentData(bookData) {
bookData.forEach((book) => {
//generate random sku number
const sku = book.sku
var random = sku[Math.floor(Math.random() * sku.length - 1)];
document.getElementById("message").innerHTML = sku[random];
});
wrap.innerHTML += `<tr>
<td>${book.sku}</td>
<td>${book.price}</td>
</tr>`
}
expected output: 101ZS536
current output: Z
// example of the data
[{sku: '101ZS536',
price: 4.37
},
{
sku: '10134QYT',
price: 42.61
},
{
sku: '10134QYT',
price: 53.31
},
{
sku: '10134QYT',
price: 0
},
{
sku: '10134QYT',
price: 3.46
}
]
Any advice or suggestions will be highly appreciated.
bookData? Why do you use.forEach()? What isbook.sku/sku? If you answer all those questions you should find the source of your problem.zbecauseskuvalue is set equal to[1,0,1,Z,S,5,3,6]. i.e. the value ofbook.skubookDataholds the entire data,.forEach()goes over each object in the data andbook.skureturns each book sku number from each object. I am trying to retrieve 1 of those sku numbers randomly.