1

I am trying to count number of occurrences of number present in array.
Logic
So I already have one array that contains numbers, so I want to push only unique numbers into another array. Also I have another array that contains Counts of each number.

CODE :

<html>
   <body>

      <script language="javascript" type="text/javascript">
         <!--
          var numbers = [ 2, 1, 2, 1, 3, 4, 2];
          var count = [];
          var newNumbers = [];

          newNumbers[0] = numbers[0];
          count[0] = 1;

          for(var i = 1 ; i < numbers.length ; i++){
              for(var j = 0 ; j < newNumbers.length ; j++){
                  if(numbers[i] == newNumbers[j]){
                      document.write("<br/>" + "Number Already Present" + " " +numbers[i]);
                  count[j] = count[j]++;

                  }else{
                      newNumbers.push(numbers[i]);
                  }
              }
          }
           for(var j = 0 ; j < newNumbers.length ; j++){
               document.write(newNumbers[j]);
           }
         //-->
      </script>

   </body>
</html>


Please help !

3
  • Guide yourself with this example. stackoverflow.com/a/5668029/5286400 Commented Jul 17, 2017 at 16:43
  • @VIX : Thanks, got little help, but I also want an array with unique numbers. Commented Jul 17, 2017 at 17:07
  • @mayankbisht Something like this? stackoverflow.com/a/11247412/5286400 Commented Jul 17, 2017 at 17:10

1 Answer 1

8

If you use an object, its more easy:

var count = {};
numbers.forEach(number => count[number] = (count[number] || 0) +1);

So you can do

count[2]; //3 <= 2 appears 3/times

Or the same with a Map:

var count = new Map();
numbers.forEach(number => count.set(count.get(number) + 1));

count.get(2)
Sign up to request clarification or add additional context in comments.

2 Comments

I couldn't understand the logic, please explain .
@mayankbisht Which part of the logic don't you understand? Break it down into individual steps and you should be enlightened.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.