Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

add text to end of array items depending on the item number

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading