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

trying to create an array that prints out: how many there is of each value in an ARRAY

info before: i have halfway succeded, as i managed to print out it and it didnt loop crazy, however i did not manage to find the reason why it still prints out a undefinded


HTML: <button id="btn">button</button>
<label id="textarea"></label>

       var tall = [4, 5, 2, 3, 4, 6, 1, 2, 0, 9, 7, 6, 8, 5, 6, 4, 2, 3, 5]
    var btn = document.getElementById("btn");
    tall.sort(function(a, b){return a-b})
    btn.onclick =  function(){
        
            for( var i = 0; i < tall.length; i++){
                a = 0;
            for(var j = 0; j<i ; j++){
                a++;
                tall.splice(i, 2)
                document.write("number "+tall[i]+" is "+ a+" times<br>")
                
            }

        }
    }

>Solution :

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

  • we can use reduce to calculate how many times number is shown
  • then we can use Object.entries with forEach – to show data to UI
    var tall = [4, 5, 2, 3, 4, 6, 1, 2, 0, 9, 7, 6, 8, 5, 6, 4, 2, 3, 5]
    var btn = document.getElementById("btn");

    btn.onclick =  function(){
        const objectResult = tall.reduce((a,c) => (a.hasOwnProperty(c) ? {...a, [c]: a[c] + 1} : {...a, [c]: 1}), {});

        Object.entries(objectResult).forEach(([number, times]) => document.write(`number: ${number} is ${times} times<br>`))


    }
<button id="btn">button</button>
<label id="textarea"></label>
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