0

It's still old school JS week for newbies at the academy.

I have created an input that makes it possible for a user to put some numbers in a input to write out an array.

Now what I'm trying to do next is writing out a paragraph with a counter for each number, like with how many times the number has been used.

If the array was [0,0,1,1,1,2,2,2,2];

And I want it to write it out something like this:

"How many times does your number appears in your array:"
0: 2
1: 3
2: 4

So far I got it to print out the numbers from the input, but I can't find a way to make it write out like above.

    var numbers = [];
    
    function numbarray() {
        numbers.push(document.getElementById("box").value);
    
        document.getElementById("text1").innerHTML = "";
        document.getElementById("text1").innerHTML += numbers.join(", ");
    
        }
       <input type="text" id="box" placeholder="0-9 with comma" />
       <input type="button" value="Click" onclick="numbarray()" />
       <br>
       Your array:<span id="text1"></span><br>

After tinkering, failing and googling since yesterday morning I've figure I try out SO again, since I've learned more from this site then I could ever imagine.

Thank you so much in advance

1
  • 1
    are you having issues displaying the data or calculating how many times each number is used? Commented Sep 25, 2015 at 19:51

4 Answers 4

2

This solution features an object for counting the frequency of the numbers with a focus of occurrence.

function count() {
    var numbers = document.getElementById("box").value
            .split(',')
            .map(Number)
            .filter(isFinite),
        distribution = numbers.reduce(function (r, a) {
            r[a] = (r[a] || 0) + 1;
            return r;
        }, {});

    document.getElementById("text1").innerHTML = numbers.join(", ");
    document.getElementById("distribution").innerHTML = Object.keys(distribution)
        .sort(function (a, b) {
            return distribution[b] - distribution[a];
        })
        .map(function (k) {
            return k + ': ' + distribution[k];
        }).join('<br>');
}
<input type="text" id="box" placeholder="0-9 with comma" />
<input type="button" value="Click" onclick="count()" /><br>
Your array: <span id="text1"></span><br>
How many times does your number appears in your array:<br>
<div id="distribution"></div>

Sign up to request clarification or add additional context in comments.

3 Comments

'tis the cleanest of the bunch for sure. Could throw a .sort(function(a,b) { return distribution[a] == distribution[b] ? 0 : (distribution[a] < distribution[b] ? 1 : -1) }) in between the keys/map for giggles. This one gets my vote.
I need more sleep... I usually do it that way, too. Meh. +1 all around.
Thanks alot for your help @NinaScholz! I've never touched the Object option before so I didn't quite understand it (hopefully I will by the end of the year ^^,) But damn, this was some amazing code! Thanks again for taking the time :)
1

    var numbers = [];
    
    function numbarray() {
        numbers = [];
        numbers = numbers.concat(document.getElementById("box").value.split(','));
        var hash = {};
        for(var i=0; i<numbers.length; i++) { 
           if (typeof hash[numbers[i]] === 'undefined') hash[numbers[i]] = 0;
           hash[numbers[i]] ++;
        }
    
        document.getElementById("text1").innerHTML = "";
        for(var k in hash) {
           document.getElementById("text1").innerHTML += k + ': ' + hash[k] + '\n';
        }
        }
       <input type="text" id="box" placeholder="0-9 with comma" />
       <input type="button" value="Click" onclick="numbarray()" />
       <br>
       Your array:<span id="text1"></span><br>

1 Comment

Thanks @KrisOye for this! These are stuff I have played around with lately so I understood most of the code :) Will use your awesome input and try to use it the best way I can! Cheers! If you like, help\mentor people (not only on SO) I would be honored and grateful if I could pitch you some code once in a while :D
0
function numbarray() {
    var nums = {}; // Use a dictionary for tallying numbers
    var numStrings = document.getElementById("box").value.split(","); // Split by commas
    // Just tally up each number
    for (var i = 0; i < numStrings.length; i++){
        var num = numStrings[i];
        if (num in nums){
            nums[num]++;
        }
        else {
            nums[num] = 1;
        }
    }
    var keys_ = Object.keys(nums); // Get the keys and sort them
    keys_.sort();
    document.getElementById("text1").innerHTML = "<br>"; // Reset the html
    for (var key in keys_){
        // Print out each number and its tally
        document.getElementById("text1").innerHTML = key + ": " + nums[key] + "<br>";
    }
}

1 Comment

He beat me to the punch and his sorts the keys (prettier).
0

Not sure if I totally understand what you are trying to do, but if you want to display the count of each number, you should first get the count of each number, then place them in your DOM, through a function such as:

var numbers = [];

var numbersObject = {};

function numbarray() {

  numbers.push(document.getElementById("box").value);

//put numbers in object to get count of each
    for(i=0; i<numbers.length; i++){
       if(numbersObject[numbers[i]]){
           numbersObject[numbers[i]]++
       }else{
           numbersObject[numbers[i]] = 1
       }
    }

 //prepare HTML

   var content = '';

    for(var key in numbersObject){
      content += key + ':' + numbersObject[key] + '<br>';
    }

    document.getElementById("text1").innerHTML = content

}

1 Comment

Without splitting though you would have to add each number individually.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.