I’ve got a dropdown list of numbers which I intend to use to track my miles. I want to add the text ‘miles’ after the number but if the number is 1, I want to add ‘mile’.
unit = miles |
arrayOfArrays = [0, 1, 2, 3, 4, 5, 6, 7, 8]
Here is my script
function showQtyNumbers(el, arrayOfArrays, unit) {
alert(arrayOfArrays);
el.innerHTML = '';
arrayOfArrays.forEach(function(r) {
var option = document.createElement('option');
option.setAttribute('value', r);
option.text = r + ' ' + unit;
el.appendChild(option);
});
}
That gives me the results: 0 miles, 1 miles, 2 miles etc.
I’ve tried the following but it does not work.
function showQtyNumbers(el, arrayOfArrays, unit) {
number1 = arrayOfArrays.find(e => e === 1)
el.innerHTML = '';
arrayOfArrays.forEach(function(r) {
var option = document.createElement('option');
if (r.find(e => e === 1)) {
r + unit.substring(0, unit.length - 1)
} else {
option.text = r + unit;
};
option.setAttribute('value', r);
el.appendChild(option);
});
}
I Know arrayOfArrays.find(e => e === 1) finds 1 but I don’t know how to do it in forEach.
>Solution :
Why don’t you pass the value for unit to the function as singular and append an ‘s’ if the value is not 1? Like this:
if(r!=1){ option.text = r + unit +"s"; }else{ option.text = r + unit; }