Idiomatically find the number of occurrences a given value has in an array











up vote
31
down vote

favorite
18












I have an array with repeating values. I would like to find the number of occurrences for any given value.



For example, if I have an array defined as so: var dataset = [2,2,4,2,6,4,7,8];, I want to find the number of occurrences of a certain value in the array. That is, the program should show that if I have 3 occurrences of the value 2, 1 occurrence of the value 6, and so on.



What's the most idiomatic/elegant way to do this?










share|improve this question




























    up vote
    31
    down vote

    favorite
    18












    I have an array with repeating values. I would like to find the number of occurrences for any given value.



    For example, if I have an array defined as so: var dataset = [2,2,4,2,6,4,7,8];, I want to find the number of occurrences of a certain value in the array. That is, the program should show that if I have 3 occurrences of the value 2, 1 occurrence of the value 6, and so on.



    What's the most idiomatic/elegant way to do this?










    share|improve this question


























      up vote
      31
      down vote

      favorite
      18









      up vote
      31
      down vote

      favorite
      18






      18





      I have an array with repeating values. I would like to find the number of occurrences for any given value.



      For example, if I have an array defined as so: var dataset = [2,2,4,2,6,4,7,8];, I want to find the number of occurrences of a certain value in the array. That is, the program should show that if I have 3 occurrences of the value 2, 1 occurrence of the value 6, and so on.



      What's the most idiomatic/elegant way to do this?










      share|improve this question















      I have an array with repeating values. I would like to find the number of occurrences for any given value.



      For example, if I have an array defined as so: var dataset = [2,2,4,2,6,4,7,8];, I want to find the number of occurrences of a certain value in the array. That is, the program should show that if I have 3 occurrences of the value 2, 1 occurrence of the value 6, and so on.



      What's the most idiomatic/elegant way to do this?







      javascript arrays






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jul 29 '17 at 7:04

























      asked Jun 26 '13 at 6:46









      Shrey Gupta

      3,36443465




      3,36443465
























          10 Answers
          10






          active

          oldest

          votes

















          up vote
          69
          down vote



          accepted










          reduce is more appropriate here than filter as it doesn't build a temporary array just for counting.






          var dataset = [2,2,4,2,6,4,7,8];
          var search = 2;

          var count = dataset.reduce(function(n, val) {
          return n + (val === search);
          }, 0);

          console.log(count);





          Note that it's easy to extend that to use a custom matching predicate, for example, to count objects that have a specific property:






          people = [
          {name: 'Mary', gender: 'girl'},
          {name: 'Paul', gender: 'boy'},
          {name: 'John', gender: 'boy'},
          {name: 'Lisa', gender: 'girl'},
          {name: 'Bill', gender: 'boy'},
          {name: 'Maklatura', gender: 'girl'}
          ]

          var numBoys = people.reduce(function (n, person) {
          return n + (person.gender == 'boy');
          }, 0);

          console.log(numBoys);





          Counting all items, that is, making an object like {x:count of xs} is complicated in javascript, because object keys can only be strings, so you can't reliably count an array with mixed types. Still, the following simple solution will work well in most cases:






          count = function (ary, classifier) {
          classifier = classifier || String;
          return ary.reduce(function (counter, item) {
          var p = classifier(item);
          counter[p] = counter.hasOwnProperty(p) ? counter[p] + 1 : 1;
          return counter;
          }, {})
          };

          people = [
          {name: 'Mary', gender: 'girl'},
          {name: 'Paul', gender: 'boy'},
          {name: 'John', gender: 'boy'},
          {name: 'Lisa', gender: 'girl'},
          {name: 'Bill', gender: 'boy'},
          {name: 'Maklatura', gender: 'girl'}
          ];

          // If you don't provide a `classifier` this simply counts different elements:

          cc = count([1, 2, 2, 2, 3, 1]);
          console.log(cc);

          // With a `classifier` you can group elements by specific property:

          countByGender = count(people, function (item) {
          return item.gender
          });
          console.log(countByGender);





          2017 update



          In ES6, you use the Map object to reliably count objects of arbitrary types:






          class Counter extends Map {
          constructor(iter, key=null) {
          super();
          this.key = key || (x => x);
          for (let x of iter) {
          this.add(x);
          }
          }
          add(x) {
          x = this.key(x);
          this.set(x, (this.get(x) || 0) + 1);
          }
          }

          // again, with no classifier just count distinct elements

          results = new Counter([1, 2, 3, 1, 2, 3, 1, 2, 2]);
          for (let [number, times] of results.entries())
          console.log('%s occurs %s times', number, times);


          // counting objects

          people = [
          {name: 'Mary', gender: 'girl'},
          {name: 'John', gender: 'boy'},
          {name: 'Lisa', gender: 'girl'},
          {name: 'Bill', gender: 'boy'},
          {name: 'Maklatura', gender: 'girl'}
          ];


          chessChampions = {
          2010: people[0],
          2012: people[0],
          2013: people[2],
          2014: people[0],
          2015: people[2],
          };

          results = new Counter(Object.values(chessChampions));
          for (let [person, times] of results.entries())
          console.log('%s won %s times', person.name, times);

          // you can also provide a classifier as in the above

          byGender = new Counter(people, x => x.gender);
          for (let g of ['boy', 'girl'])
          console.log("there are %s %ss", byGender.get(g), g);








          share|improve this answer























          • @thg435 I tried using this and ended up with an undefined value...and also, does the reduce method still preserve the array? I would like to keep the array unchanged.
            – Shrey Gupta
            Jun 27 '13 at 2:28










          • @Bagavatu: post your code/fiddle. No, reduce doesn't change the array.
            – georg
            Jun 27 '13 at 9:12


















          up vote
          11
          down vote













          Newer browsers only due to using Array.filter



          var dataset = [2,2,4,2,6,4,7,8];
          var search = 2;
          var occurrences = dataset.filter(function(val) {
          return val === search;
          }).length;
          console.log(occurrences); // 3





          share|improve this answer



















          • 3




            Or, shorter: occurrences = dataset.filter(v => v === search).length
            – Ninjakannon
            May 20 '17 at 23:53




















          up vote
          9
          down vote













          array.filter(c => c === searchvalue).length;





          share|improve this answer






























            up vote
            7
            down vote













            Here is one way to show ALL counts at once:



            var dataset = [2, 2, 4, 2, 6, 4, 7, 8];
            var counts = {}, i, value;
            for (i = 0; i < dataset.length; i++) {
            value = dataset[i];
            if (typeof counts[value] === "undefined") {
            counts[value] = 1;
            } else {
            counts[value]++;
            }
            }
            console.log(counts);
            // Object {
            // 2: 3,
            // 4: 2,
            // 6: 1,
            // 7: 1,
            // 8: 1
            //}





            share|improve this answer






























              up vote
              6
              down vote













              Using a normal loop, you can find the occurrences consistently and reliably:



              const dataset = [2,2,4,2,6,4,7,8];

              function getNumMatches(array, valToFind) {
              let numMatches = 0;
              for (let i = 0, j = array.length; i < j; i += 1) {
              if (array[i] === valToFind) {
              numMatches += 1;
              }
              }
              return numMatches;
              }

              alert(getNumMatches(dataset, 2)); // should alert 3


              DEMO: https://jsfiddle.net/a7q9k4uu/



              To make it more generic, the function could accept a predicate function with custom logic (returning true/false) which would determine the final count. For example:



              const dataset = [2,2,4,2,6,4,7,8];

              function getNumMatches(array, predicate) {
              let numMatches = 0;
              for (let i = 0, j = array.length; i < j; i += 1) {
              const current = array[i];
              if (predicate(current) === true) {
              numMatches += 1;
              }
              }
              return numMatches;
              }

              const numFound = getNumMatches(dataset, (item) => {
              return item === 2;
              });

              alert(numFound); // should alert 3


              DEMO: https://jsfiddle.net/57en9nar/1/






              share|improve this answer























              • +1 For wrapping in a semantically understandable and readable function. Although I would call it getNumMatches or getNumOccurrences. findOccurrences sounds like you're trying to return the occurrences themselves (an array) rather than how many of them there are (a number).
                – Adam Zerner
                Feb 23 at 17:52










              • Also, as others have mentioned, you can pass in a predicate function instead of a value to test for matches. Demo: repl.it/repls/DecimalFrostyTechnicians
                – Adam Zerner
                Feb 23 at 17:57










              • @AdamZerner Agreed, thanks for the input. Updated with your recommendations
                – Ian
                Feb 23 at 18:05


















              up vote
              5
              down vote













              var dataset = [2,2,4,2,6,4,7,8], count = {}

              dataset.forEach(function(el){
              count[el] = count[el] + 1 || 1
              });

              console.log(count)

              // {
              // 2: 3,
              // 4: 2,
              // 6: 1,
              // 7: 1,
              // 8: 1
              // }





              share|improve this answer





















              • He checks on every loop if the key already exists. If yes increment the current value of the by one. If not insert 1 for this key.
                – TdoubleG
                Sep 28 '17 at 9:06




















              up vote
              3
              down vote













              You can do with use of array.reduce(callback[, initialValue]) method in JavaScript 1.8



              var dataset = [2,2,4,2,6,4,7,8],
              dataWithCount = dataset.reduce( function( o , v ) {

              if ( ! o[ v ] ) {
              o[ v ] = 1 ;
              } else {
              o[ v ] = o[ v ] + 1;
              }

              return o ;

              }, {} );

              // print data with count.
              for( var i in dataWithCount ){
              console.log( i + 'occured ' + dataWithCount[i] + 'times ' );
              }

              // find one number
              var search = 2,
              count = dataWithCount[ search ] || 0;





              share|improve this answer






























                up vote
                2
                down vote













                You can count all items in an array, in a single line, using reduce.



                .reduce((a,b) => (a[b] = a[b] + 1 || 1) && a, {})


                This will yield an object, whose keys are the distinct elements in the array and values are the count of occurences of elements in the array. You can then access one or more of the counts by accessing a corresponding key on the object.



                For example if you were to wrap the above in a function called count():



                function count(arr) {
                return arr.reduce((a,b) => (a[b] = a[b] + 1 || 1) && a, {})
                }

                count(['example']) // { example: 1 }
                count([2,2,4,2,6,4,7,8])[2] // 3





                share|improve this answer




























                  up vote
                  0
                  down vote













                  I've found it more useful to end up with a list of objects with a key for what is being counted and a key for the count:



                  const data = [2,2,4,2,6,4,7,8]
                  let counted =
                  for (var c of data) {
                  const alreadyCounted = counted.map(c => c.name)
                  if (alreadyCounted.includes(c)) {
                  counted[alreadyCounted.indexOf(c)].count += 1
                  } else {
                  counted.push({ 'name': c, 'count': 1})
                  }
                  }
                  console.log(counted)


                  which returns:



                  [ { name: 2, count: 3 },
                  { name: 4, count: 2 },
                  { name: 6, count: 1 },
                  { name: 7, count: 1 },
                  { name: 8, count: 1 } ]


                  It isn't the cleanest method, and if anyone knows how to achieve the same result with reduce let me know. However, it does produce a result that's fairly easy to work with.






                  share|improve this answer




























                    up vote
                    0
                    down vote













                    First, you can go with Brute Force Solution by going with Linear Search.



                    public int LinearSearchcount(int A, int data){
                    int count=0;
                    for(int i=0;i<A.length;i++) {
                    if(A[i]==data) count++;
                    }
                    return count;
                    }


                    However, for going with this, we get Time complexity as O(n).But by going with Binary search, we can improve our Complexity.






                    share|improve this answer























                      Your Answer






                      StackExchange.ifUsing("editor", function () {
                      StackExchange.using("externalEditor", function () {
                      StackExchange.using("snippets", function () {
                      StackExchange.snippets.init();
                      });
                      });
                      }, "code-snippets");

                      StackExchange.ready(function() {
                      var channelOptions = {
                      tags: "".split(" "),
                      id: "1"
                      };
                      initTagRenderer("".split(" "), "".split(" "), channelOptions);

                      StackExchange.using("externalEditor", function() {
                      // Have to fire editor after snippets, if snippets enabled
                      if (StackExchange.settings.snippets.snippetsEnabled) {
                      StackExchange.using("snippets", function() {
                      createEditor();
                      });
                      }
                      else {
                      createEditor();
                      }
                      });

                      function createEditor() {
                      StackExchange.prepareEditor({
                      heartbeatType: 'answer',
                      convertImagesToLinks: true,
                      noModals: true,
                      showLowRepImageUploadWarning: true,
                      reputationToPostImages: 10,
                      bindNavPrevention: true,
                      postfix: "",
                      imageUploader: {
                      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                      allowUrls: true
                      },
                      onDemand: true,
                      discardSelector: ".discard-answer"
                      ,immediatelyShowMarkdownHelp:true
                      });


                      }
                      });














                      draft saved

                      draft discarded


















                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f17313268%2fidiomatically-find-the-number-of-occurrences-a-given-value-has-in-an-array%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown

























                      10 Answers
                      10






                      active

                      oldest

                      votes








                      10 Answers
                      10






                      active

                      oldest

                      votes









                      active

                      oldest

                      votes






                      active

                      oldest

                      votes








                      up vote
                      69
                      down vote



                      accepted










                      reduce is more appropriate here than filter as it doesn't build a temporary array just for counting.






                      var dataset = [2,2,4,2,6,4,7,8];
                      var search = 2;

                      var count = dataset.reduce(function(n, val) {
                      return n + (val === search);
                      }, 0);

                      console.log(count);





                      Note that it's easy to extend that to use a custom matching predicate, for example, to count objects that have a specific property:






                      people = [
                      {name: 'Mary', gender: 'girl'},
                      {name: 'Paul', gender: 'boy'},
                      {name: 'John', gender: 'boy'},
                      {name: 'Lisa', gender: 'girl'},
                      {name: 'Bill', gender: 'boy'},
                      {name: 'Maklatura', gender: 'girl'}
                      ]

                      var numBoys = people.reduce(function (n, person) {
                      return n + (person.gender == 'boy');
                      }, 0);

                      console.log(numBoys);





                      Counting all items, that is, making an object like {x:count of xs} is complicated in javascript, because object keys can only be strings, so you can't reliably count an array with mixed types. Still, the following simple solution will work well in most cases:






                      count = function (ary, classifier) {
                      classifier = classifier || String;
                      return ary.reduce(function (counter, item) {
                      var p = classifier(item);
                      counter[p] = counter.hasOwnProperty(p) ? counter[p] + 1 : 1;
                      return counter;
                      }, {})
                      };

                      people = [
                      {name: 'Mary', gender: 'girl'},
                      {name: 'Paul', gender: 'boy'},
                      {name: 'John', gender: 'boy'},
                      {name: 'Lisa', gender: 'girl'},
                      {name: 'Bill', gender: 'boy'},
                      {name: 'Maklatura', gender: 'girl'}
                      ];

                      // If you don't provide a `classifier` this simply counts different elements:

                      cc = count([1, 2, 2, 2, 3, 1]);
                      console.log(cc);

                      // With a `classifier` you can group elements by specific property:

                      countByGender = count(people, function (item) {
                      return item.gender
                      });
                      console.log(countByGender);





                      2017 update



                      In ES6, you use the Map object to reliably count objects of arbitrary types:






                      class Counter extends Map {
                      constructor(iter, key=null) {
                      super();
                      this.key = key || (x => x);
                      for (let x of iter) {
                      this.add(x);
                      }
                      }
                      add(x) {
                      x = this.key(x);
                      this.set(x, (this.get(x) || 0) + 1);
                      }
                      }

                      // again, with no classifier just count distinct elements

                      results = new Counter([1, 2, 3, 1, 2, 3, 1, 2, 2]);
                      for (let [number, times] of results.entries())
                      console.log('%s occurs %s times', number, times);


                      // counting objects

                      people = [
                      {name: 'Mary', gender: 'girl'},
                      {name: 'John', gender: 'boy'},
                      {name: 'Lisa', gender: 'girl'},
                      {name: 'Bill', gender: 'boy'},
                      {name: 'Maklatura', gender: 'girl'}
                      ];


                      chessChampions = {
                      2010: people[0],
                      2012: people[0],
                      2013: people[2],
                      2014: people[0],
                      2015: people[2],
                      };

                      results = new Counter(Object.values(chessChampions));
                      for (let [person, times] of results.entries())
                      console.log('%s won %s times', person.name, times);

                      // you can also provide a classifier as in the above

                      byGender = new Counter(people, x => x.gender);
                      for (let g of ['boy', 'girl'])
                      console.log("there are %s %ss", byGender.get(g), g);








                      share|improve this answer























                      • @thg435 I tried using this and ended up with an undefined value...and also, does the reduce method still preserve the array? I would like to keep the array unchanged.
                        – Shrey Gupta
                        Jun 27 '13 at 2:28










                      • @Bagavatu: post your code/fiddle. No, reduce doesn't change the array.
                        – georg
                        Jun 27 '13 at 9:12















                      up vote
                      69
                      down vote



                      accepted










                      reduce is more appropriate here than filter as it doesn't build a temporary array just for counting.






                      var dataset = [2,2,4,2,6,4,7,8];
                      var search = 2;

                      var count = dataset.reduce(function(n, val) {
                      return n + (val === search);
                      }, 0);

                      console.log(count);





                      Note that it's easy to extend that to use a custom matching predicate, for example, to count objects that have a specific property:






                      people = [
                      {name: 'Mary', gender: 'girl'},
                      {name: 'Paul', gender: 'boy'},
                      {name: 'John', gender: 'boy'},
                      {name: 'Lisa', gender: 'girl'},
                      {name: 'Bill', gender: 'boy'},
                      {name: 'Maklatura', gender: 'girl'}
                      ]

                      var numBoys = people.reduce(function (n, person) {
                      return n + (person.gender == 'boy');
                      }, 0);

                      console.log(numBoys);





                      Counting all items, that is, making an object like {x:count of xs} is complicated in javascript, because object keys can only be strings, so you can't reliably count an array with mixed types. Still, the following simple solution will work well in most cases:






                      count = function (ary, classifier) {
                      classifier = classifier || String;
                      return ary.reduce(function (counter, item) {
                      var p = classifier(item);
                      counter[p] = counter.hasOwnProperty(p) ? counter[p] + 1 : 1;
                      return counter;
                      }, {})
                      };

                      people = [
                      {name: 'Mary', gender: 'girl'},
                      {name: 'Paul', gender: 'boy'},
                      {name: 'John', gender: 'boy'},
                      {name: 'Lisa', gender: 'girl'},
                      {name: 'Bill', gender: 'boy'},
                      {name: 'Maklatura', gender: 'girl'}
                      ];

                      // If you don't provide a `classifier` this simply counts different elements:

                      cc = count([1, 2, 2, 2, 3, 1]);
                      console.log(cc);

                      // With a `classifier` you can group elements by specific property:

                      countByGender = count(people, function (item) {
                      return item.gender
                      });
                      console.log(countByGender);





                      2017 update



                      In ES6, you use the Map object to reliably count objects of arbitrary types:






                      class Counter extends Map {
                      constructor(iter, key=null) {
                      super();
                      this.key = key || (x => x);
                      for (let x of iter) {
                      this.add(x);
                      }
                      }
                      add(x) {
                      x = this.key(x);
                      this.set(x, (this.get(x) || 0) + 1);
                      }
                      }

                      // again, with no classifier just count distinct elements

                      results = new Counter([1, 2, 3, 1, 2, 3, 1, 2, 2]);
                      for (let [number, times] of results.entries())
                      console.log('%s occurs %s times', number, times);


                      // counting objects

                      people = [
                      {name: 'Mary', gender: 'girl'},
                      {name: 'John', gender: 'boy'},
                      {name: 'Lisa', gender: 'girl'},
                      {name: 'Bill', gender: 'boy'},
                      {name: 'Maklatura', gender: 'girl'}
                      ];


                      chessChampions = {
                      2010: people[0],
                      2012: people[0],
                      2013: people[2],
                      2014: people[0],
                      2015: people[2],
                      };

                      results = new Counter(Object.values(chessChampions));
                      for (let [person, times] of results.entries())
                      console.log('%s won %s times', person.name, times);

                      // you can also provide a classifier as in the above

                      byGender = new Counter(people, x => x.gender);
                      for (let g of ['boy', 'girl'])
                      console.log("there are %s %ss", byGender.get(g), g);








                      share|improve this answer























                      • @thg435 I tried using this and ended up with an undefined value...and also, does the reduce method still preserve the array? I would like to keep the array unchanged.
                        – Shrey Gupta
                        Jun 27 '13 at 2:28










                      • @Bagavatu: post your code/fiddle. No, reduce doesn't change the array.
                        – georg
                        Jun 27 '13 at 9:12













                      up vote
                      69
                      down vote



                      accepted







                      up vote
                      69
                      down vote



                      accepted






                      reduce is more appropriate here than filter as it doesn't build a temporary array just for counting.






                      var dataset = [2,2,4,2,6,4,7,8];
                      var search = 2;

                      var count = dataset.reduce(function(n, val) {
                      return n + (val === search);
                      }, 0);

                      console.log(count);





                      Note that it's easy to extend that to use a custom matching predicate, for example, to count objects that have a specific property:






                      people = [
                      {name: 'Mary', gender: 'girl'},
                      {name: 'Paul', gender: 'boy'},
                      {name: 'John', gender: 'boy'},
                      {name: 'Lisa', gender: 'girl'},
                      {name: 'Bill', gender: 'boy'},
                      {name: 'Maklatura', gender: 'girl'}
                      ]

                      var numBoys = people.reduce(function (n, person) {
                      return n + (person.gender == 'boy');
                      }, 0);

                      console.log(numBoys);





                      Counting all items, that is, making an object like {x:count of xs} is complicated in javascript, because object keys can only be strings, so you can't reliably count an array with mixed types. Still, the following simple solution will work well in most cases:






                      count = function (ary, classifier) {
                      classifier = classifier || String;
                      return ary.reduce(function (counter, item) {
                      var p = classifier(item);
                      counter[p] = counter.hasOwnProperty(p) ? counter[p] + 1 : 1;
                      return counter;
                      }, {})
                      };

                      people = [
                      {name: 'Mary', gender: 'girl'},
                      {name: 'Paul', gender: 'boy'},
                      {name: 'John', gender: 'boy'},
                      {name: 'Lisa', gender: 'girl'},
                      {name: 'Bill', gender: 'boy'},
                      {name: 'Maklatura', gender: 'girl'}
                      ];

                      // If you don't provide a `classifier` this simply counts different elements:

                      cc = count([1, 2, 2, 2, 3, 1]);
                      console.log(cc);

                      // With a `classifier` you can group elements by specific property:

                      countByGender = count(people, function (item) {
                      return item.gender
                      });
                      console.log(countByGender);





                      2017 update



                      In ES6, you use the Map object to reliably count objects of arbitrary types:






                      class Counter extends Map {
                      constructor(iter, key=null) {
                      super();
                      this.key = key || (x => x);
                      for (let x of iter) {
                      this.add(x);
                      }
                      }
                      add(x) {
                      x = this.key(x);
                      this.set(x, (this.get(x) || 0) + 1);
                      }
                      }

                      // again, with no classifier just count distinct elements

                      results = new Counter([1, 2, 3, 1, 2, 3, 1, 2, 2]);
                      for (let [number, times] of results.entries())
                      console.log('%s occurs %s times', number, times);


                      // counting objects

                      people = [
                      {name: 'Mary', gender: 'girl'},
                      {name: 'John', gender: 'boy'},
                      {name: 'Lisa', gender: 'girl'},
                      {name: 'Bill', gender: 'boy'},
                      {name: 'Maklatura', gender: 'girl'}
                      ];


                      chessChampions = {
                      2010: people[0],
                      2012: people[0],
                      2013: people[2],
                      2014: people[0],
                      2015: people[2],
                      };

                      results = new Counter(Object.values(chessChampions));
                      for (let [person, times] of results.entries())
                      console.log('%s won %s times', person.name, times);

                      // you can also provide a classifier as in the above

                      byGender = new Counter(people, x => x.gender);
                      for (let g of ['boy', 'girl'])
                      console.log("there are %s %ss", byGender.get(g), g);








                      share|improve this answer














                      reduce is more appropriate here than filter as it doesn't build a temporary array just for counting.






                      var dataset = [2,2,4,2,6,4,7,8];
                      var search = 2;

                      var count = dataset.reduce(function(n, val) {
                      return n + (val === search);
                      }, 0);

                      console.log(count);





                      Note that it's easy to extend that to use a custom matching predicate, for example, to count objects that have a specific property:






                      people = [
                      {name: 'Mary', gender: 'girl'},
                      {name: 'Paul', gender: 'boy'},
                      {name: 'John', gender: 'boy'},
                      {name: 'Lisa', gender: 'girl'},
                      {name: 'Bill', gender: 'boy'},
                      {name: 'Maklatura', gender: 'girl'}
                      ]

                      var numBoys = people.reduce(function (n, person) {
                      return n + (person.gender == 'boy');
                      }, 0);

                      console.log(numBoys);





                      Counting all items, that is, making an object like {x:count of xs} is complicated in javascript, because object keys can only be strings, so you can't reliably count an array with mixed types. Still, the following simple solution will work well in most cases:






                      count = function (ary, classifier) {
                      classifier = classifier || String;
                      return ary.reduce(function (counter, item) {
                      var p = classifier(item);
                      counter[p] = counter.hasOwnProperty(p) ? counter[p] + 1 : 1;
                      return counter;
                      }, {})
                      };

                      people = [
                      {name: 'Mary', gender: 'girl'},
                      {name: 'Paul', gender: 'boy'},
                      {name: 'John', gender: 'boy'},
                      {name: 'Lisa', gender: 'girl'},
                      {name: 'Bill', gender: 'boy'},
                      {name: 'Maklatura', gender: 'girl'}
                      ];

                      // If you don't provide a `classifier` this simply counts different elements:

                      cc = count([1, 2, 2, 2, 3, 1]);
                      console.log(cc);

                      // With a `classifier` you can group elements by specific property:

                      countByGender = count(people, function (item) {
                      return item.gender
                      });
                      console.log(countByGender);





                      2017 update



                      In ES6, you use the Map object to reliably count objects of arbitrary types:






                      class Counter extends Map {
                      constructor(iter, key=null) {
                      super();
                      this.key = key || (x => x);
                      for (let x of iter) {
                      this.add(x);
                      }
                      }
                      add(x) {
                      x = this.key(x);
                      this.set(x, (this.get(x) || 0) + 1);
                      }
                      }

                      // again, with no classifier just count distinct elements

                      results = new Counter([1, 2, 3, 1, 2, 3, 1, 2, 2]);
                      for (let [number, times] of results.entries())
                      console.log('%s occurs %s times', number, times);


                      // counting objects

                      people = [
                      {name: 'Mary', gender: 'girl'},
                      {name: 'John', gender: 'boy'},
                      {name: 'Lisa', gender: 'girl'},
                      {name: 'Bill', gender: 'boy'},
                      {name: 'Maklatura', gender: 'girl'}
                      ];


                      chessChampions = {
                      2010: people[0],
                      2012: people[0],
                      2013: people[2],
                      2014: people[0],
                      2015: people[2],
                      };

                      results = new Counter(Object.values(chessChampions));
                      for (let [person, times] of results.entries())
                      console.log('%s won %s times', person.name, times);

                      // you can also provide a classifier as in the above

                      byGender = new Counter(people, x => x.gender);
                      for (let g of ['boy', 'girl'])
                      console.log("there are %s %ss", byGender.get(g), g);








                      var dataset = [2,2,4,2,6,4,7,8];
                      var search = 2;

                      var count = dataset.reduce(function(n, val) {
                      return n + (val === search);
                      }, 0);

                      console.log(count);





                      var dataset = [2,2,4,2,6,4,7,8];
                      var search = 2;

                      var count = dataset.reduce(function(n, val) {
                      return n + (val === search);
                      }, 0);

                      console.log(count);





                      people = [
                      {name: 'Mary', gender: 'girl'},
                      {name: 'Paul', gender: 'boy'},
                      {name: 'John', gender: 'boy'},
                      {name: 'Lisa', gender: 'girl'},
                      {name: 'Bill', gender: 'boy'},
                      {name: 'Maklatura', gender: 'girl'}
                      ]

                      var numBoys = people.reduce(function (n, person) {
                      return n + (person.gender == 'boy');
                      }, 0);

                      console.log(numBoys);





                      people = [
                      {name: 'Mary', gender: 'girl'},
                      {name: 'Paul', gender: 'boy'},
                      {name: 'John', gender: 'boy'},
                      {name: 'Lisa', gender: 'girl'},
                      {name: 'Bill', gender: 'boy'},
                      {name: 'Maklatura', gender: 'girl'}
                      ]

                      var numBoys = people.reduce(function (n, person) {
                      return n + (person.gender == 'boy');
                      }, 0);

                      console.log(numBoys);





                      count = function (ary, classifier) {
                      classifier = classifier || String;
                      return ary.reduce(function (counter, item) {
                      var p = classifier(item);
                      counter[p] = counter.hasOwnProperty(p) ? counter[p] + 1 : 1;
                      return counter;
                      }, {})
                      };

                      people = [
                      {name: 'Mary', gender: 'girl'},
                      {name: 'Paul', gender: 'boy'},
                      {name: 'John', gender: 'boy'},
                      {name: 'Lisa', gender: 'girl'},
                      {name: 'Bill', gender: 'boy'},
                      {name: 'Maklatura', gender: 'girl'}
                      ];

                      // If you don't provide a `classifier` this simply counts different elements:

                      cc = count([1, 2, 2, 2, 3, 1]);
                      console.log(cc);

                      // With a `classifier` you can group elements by specific property:

                      countByGender = count(people, function (item) {
                      return item.gender
                      });
                      console.log(countByGender);





                      count = function (ary, classifier) {
                      classifier = classifier || String;
                      return ary.reduce(function (counter, item) {
                      var p = classifier(item);
                      counter[p] = counter.hasOwnProperty(p) ? counter[p] + 1 : 1;
                      return counter;
                      }, {})
                      };

                      people = [
                      {name: 'Mary', gender: 'girl'},
                      {name: 'Paul', gender: 'boy'},
                      {name: 'John', gender: 'boy'},
                      {name: 'Lisa', gender: 'girl'},
                      {name: 'Bill', gender: 'boy'},
                      {name: 'Maklatura', gender: 'girl'}
                      ];

                      // If you don't provide a `classifier` this simply counts different elements:

                      cc = count([1, 2, 2, 2, 3, 1]);
                      console.log(cc);

                      // With a `classifier` you can group elements by specific property:

                      countByGender = count(people, function (item) {
                      return item.gender
                      });
                      console.log(countByGender);





                      class Counter extends Map {
                      constructor(iter, key=null) {
                      super();
                      this.key = key || (x => x);
                      for (let x of iter) {
                      this.add(x);
                      }
                      }
                      add(x) {
                      x = this.key(x);
                      this.set(x, (this.get(x) || 0) + 1);
                      }
                      }

                      // again, with no classifier just count distinct elements

                      results = new Counter([1, 2, 3, 1, 2, 3, 1, 2, 2]);
                      for (let [number, times] of results.entries())
                      console.log('%s occurs %s times', number, times);


                      // counting objects

                      people = [
                      {name: 'Mary', gender: 'girl'},
                      {name: 'John', gender: 'boy'},
                      {name: 'Lisa', gender: 'girl'},
                      {name: 'Bill', gender: 'boy'},
                      {name: 'Maklatura', gender: 'girl'}
                      ];


                      chessChampions = {
                      2010: people[0],
                      2012: people[0],
                      2013: people[2],
                      2014: people[0],
                      2015: people[2],
                      };

                      results = new Counter(Object.values(chessChampions));
                      for (let [person, times] of results.entries())
                      console.log('%s won %s times', person.name, times);

                      // you can also provide a classifier as in the above

                      byGender = new Counter(people, x => x.gender);
                      for (let g of ['boy', 'girl'])
                      console.log("there are %s %ss", byGender.get(g), g);





                      class Counter extends Map {
                      constructor(iter, key=null) {
                      super();
                      this.key = key || (x => x);
                      for (let x of iter) {
                      this.add(x);
                      }
                      }
                      add(x) {
                      x = this.key(x);
                      this.set(x, (this.get(x) || 0) + 1);
                      }
                      }

                      // again, with no classifier just count distinct elements

                      results = new Counter([1, 2, 3, 1, 2, 3, 1, 2, 2]);
                      for (let [number, times] of results.entries())
                      console.log('%s occurs %s times', number, times);


                      // counting objects

                      people = [
                      {name: 'Mary', gender: 'girl'},
                      {name: 'John', gender: 'boy'},
                      {name: 'Lisa', gender: 'girl'},
                      {name: 'Bill', gender: 'boy'},
                      {name: 'Maklatura', gender: 'girl'}
                      ];


                      chessChampions = {
                      2010: people[0],
                      2012: people[0],
                      2013: people[2],
                      2014: people[0],
                      2015: people[2],
                      };

                      results = new Counter(Object.values(chessChampions));
                      for (let [person, times] of results.entries())
                      console.log('%s won %s times', person.name, times);

                      // you can also provide a classifier as in the above

                      byGender = new Counter(people, x => x.gender);
                      for (let g of ['boy', 'girl'])
                      console.log("there are %s %ss", byGender.get(g), g);






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Sep 21 '17 at 20:31

























                      answered Jun 26 '13 at 6:56









                      georg

                      145k34194290




                      145k34194290












                      • @thg435 I tried using this and ended up with an undefined value...and also, does the reduce method still preserve the array? I would like to keep the array unchanged.
                        – Shrey Gupta
                        Jun 27 '13 at 2:28










                      • @Bagavatu: post your code/fiddle. No, reduce doesn't change the array.
                        – georg
                        Jun 27 '13 at 9:12


















                      • @thg435 I tried using this and ended up with an undefined value...and also, does the reduce method still preserve the array? I would like to keep the array unchanged.
                        – Shrey Gupta
                        Jun 27 '13 at 2:28










                      • @Bagavatu: post your code/fiddle. No, reduce doesn't change the array.
                        – georg
                        Jun 27 '13 at 9:12
















                      @thg435 I tried using this and ended up with an undefined value...and also, does the reduce method still preserve the array? I would like to keep the array unchanged.
                      – Shrey Gupta
                      Jun 27 '13 at 2:28




                      @thg435 I tried using this and ended up with an undefined value...and also, does the reduce method still preserve the array? I would like to keep the array unchanged.
                      – Shrey Gupta
                      Jun 27 '13 at 2:28












                      @Bagavatu: post your code/fiddle. No, reduce doesn't change the array.
                      – georg
                      Jun 27 '13 at 9:12




                      @Bagavatu: post your code/fiddle. No, reduce doesn't change the array.
                      – georg
                      Jun 27 '13 at 9:12












                      up vote
                      11
                      down vote













                      Newer browsers only due to using Array.filter



                      var dataset = [2,2,4,2,6,4,7,8];
                      var search = 2;
                      var occurrences = dataset.filter(function(val) {
                      return val === search;
                      }).length;
                      console.log(occurrences); // 3





                      share|improve this answer



















                      • 3




                        Or, shorter: occurrences = dataset.filter(v => v === search).length
                        – Ninjakannon
                        May 20 '17 at 23:53

















                      up vote
                      11
                      down vote













                      Newer browsers only due to using Array.filter



                      var dataset = [2,2,4,2,6,4,7,8];
                      var search = 2;
                      var occurrences = dataset.filter(function(val) {
                      return val === search;
                      }).length;
                      console.log(occurrences); // 3





                      share|improve this answer



















                      • 3




                        Or, shorter: occurrences = dataset.filter(v => v === search).length
                        – Ninjakannon
                        May 20 '17 at 23:53















                      up vote
                      11
                      down vote










                      up vote
                      11
                      down vote









                      Newer browsers only due to using Array.filter



                      var dataset = [2,2,4,2,6,4,7,8];
                      var search = 2;
                      var occurrences = dataset.filter(function(val) {
                      return val === search;
                      }).length;
                      console.log(occurrences); // 3





                      share|improve this answer














                      Newer browsers only due to using Array.filter



                      var dataset = [2,2,4,2,6,4,7,8];
                      var search = 2;
                      var occurrences = dataset.filter(function(val) {
                      return val === search;
                      }).length;
                      console.log(occurrences); // 3






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited May 20 '17 at 23:54









                      Ninjakannon

                      2,67642645




                      2,67642645










                      answered Jun 26 '13 at 6:51









                      goat

                      25.8k54883




                      25.8k54883








                      • 3




                        Or, shorter: occurrences = dataset.filter(v => v === search).length
                        – Ninjakannon
                        May 20 '17 at 23:53
















                      • 3




                        Or, shorter: occurrences = dataset.filter(v => v === search).length
                        – Ninjakannon
                        May 20 '17 at 23:53










                      3




                      3




                      Or, shorter: occurrences = dataset.filter(v => v === search).length
                      – Ninjakannon
                      May 20 '17 at 23:53






                      Or, shorter: occurrences = dataset.filter(v => v === search).length
                      – Ninjakannon
                      May 20 '17 at 23:53












                      up vote
                      9
                      down vote













                      array.filter(c => c === searchvalue).length;





                      share|improve this answer



























                        up vote
                        9
                        down vote













                        array.filter(c => c === searchvalue).length;





                        share|improve this answer

























                          up vote
                          9
                          down vote










                          up vote
                          9
                          down vote









                          array.filter(c => c === searchvalue).length;





                          share|improve this answer














                          array.filter(c => c === searchvalue).length;






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Aug 25 '16 at 10:39









                          Liam

                          16k1675125




                          16k1675125










                          answered Aug 25 '16 at 8:19









                          Julian Wagner

                          9111




                          9111






















                              up vote
                              7
                              down vote













                              Here is one way to show ALL counts at once:



                              var dataset = [2, 2, 4, 2, 6, 4, 7, 8];
                              var counts = {}, i, value;
                              for (i = 0; i < dataset.length; i++) {
                              value = dataset[i];
                              if (typeof counts[value] === "undefined") {
                              counts[value] = 1;
                              } else {
                              counts[value]++;
                              }
                              }
                              console.log(counts);
                              // Object {
                              // 2: 3,
                              // 4: 2,
                              // 6: 1,
                              // 7: 1,
                              // 8: 1
                              //}





                              share|improve this answer



























                                up vote
                                7
                                down vote













                                Here is one way to show ALL counts at once:



                                var dataset = [2, 2, 4, 2, 6, 4, 7, 8];
                                var counts = {}, i, value;
                                for (i = 0; i < dataset.length; i++) {
                                value = dataset[i];
                                if (typeof counts[value] === "undefined") {
                                counts[value] = 1;
                                } else {
                                counts[value]++;
                                }
                                }
                                console.log(counts);
                                // Object {
                                // 2: 3,
                                // 4: 2,
                                // 6: 1,
                                // 7: 1,
                                // 8: 1
                                //}





                                share|improve this answer

























                                  up vote
                                  7
                                  down vote










                                  up vote
                                  7
                                  down vote









                                  Here is one way to show ALL counts at once:



                                  var dataset = [2, 2, 4, 2, 6, 4, 7, 8];
                                  var counts = {}, i, value;
                                  for (i = 0; i < dataset.length; i++) {
                                  value = dataset[i];
                                  if (typeof counts[value] === "undefined") {
                                  counts[value] = 1;
                                  } else {
                                  counts[value]++;
                                  }
                                  }
                                  console.log(counts);
                                  // Object {
                                  // 2: 3,
                                  // 4: 2,
                                  // 6: 1,
                                  // 7: 1,
                                  // 8: 1
                                  //}





                                  share|improve this answer














                                  Here is one way to show ALL counts at once:



                                  var dataset = [2, 2, 4, 2, 6, 4, 7, 8];
                                  var counts = {}, i, value;
                                  for (i = 0; i < dataset.length; i++) {
                                  value = dataset[i];
                                  if (typeof counts[value] === "undefined") {
                                  counts[value] = 1;
                                  } else {
                                  counts[value]++;
                                  }
                                  }
                                  console.log(counts);
                                  // Object {
                                  // 2: 3,
                                  // 4: 2,
                                  // 6: 1,
                                  // 7: 1,
                                  // 8: 1
                                  //}






                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Jun 26 '13 at 7:02

























                                  answered Jun 26 '13 at 6:56









                                  Salman A

                                  173k66332419




                                  173k66332419






















                                      up vote
                                      6
                                      down vote













                                      Using a normal loop, you can find the occurrences consistently and reliably:



                                      const dataset = [2,2,4,2,6,4,7,8];

                                      function getNumMatches(array, valToFind) {
                                      let numMatches = 0;
                                      for (let i = 0, j = array.length; i < j; i += 1) {
                                      if (array[i] === valToFind) {
                                      numMatches += 1;
                                      }
                                      }
                                      return numMatches;
                                      }

                                      alert(getNumMatches(dataset, 2)); // should alert 3


                                      DEMO: https://jsfiddle.net/a7q9k4uu/



                                      To make it more generic, the function could accept a predicate function with custom logic (returning true/false) which would determine the final count. For example:



                                      const dataset = [2,2,4,2,6,4,7,8];

                                      function getNumMatches(array, predicate) {
                                      let numMatches = 0;
                                      for (let i = 0, j = array.length; i < j; i += 1) {
                                      const current = array[i];
                                      if (predicate(current) === true) {
                                      numMatches += 1;
                                      }
                                      }
                                      return numMatches;
                                      }

                                      const numFound = getNumMatches(dataset, (item) => {
                                      return item === 2;
                                      });

                                      alert(numFound); // should alert 3


                                      DEMO: https://jsfiddle.net/57en9nar/1/






                                      share|improve this answer























                                      • +1 For wrapping in a semantically understandable and readable function. Although I would call it getNumMatches or getNumOccurrences. findOccurrences sounds like you're trying to return the occurrences themselves (an array) rather than how many of them there are (a number).
                                        – Adam Zerner
                                        Feb 23 at 17:52










                                      • Also, as others have mentioned, you can pass in a predicate function instead of a value to test for matches. Demo: repl.it/repls/DecimalFrostyTechnicians
                                        – Adam Zerner
                                        Feb 23 at 17:57










                                      • @AdamZerner Agreed, thanks for the input. Updated with your recommendations
                                        – Ian
                                        Feb 23 at 18:05















                                      up vote
                                      6
                                      down vote













                                      Using a normal loop, you can find the occurrences consistently and reliably:



                                      const dataset = [2,2,4,2,6,4,7,8];

                                      function getNumMatches(array, valToFind) {
                                      let numMatches = 0;
                                      for (let i = 0, j = array.length; i < j; i += 1) {
                                      if (array[i] === valToFind) {
                                      numMatches += 1;
                                      }
                                      }
                                      return numMatches;
                                      }

                                      alert(getNumMatches(dataset, 2)); // should alert 3


                                      DEMO: https://jsfiddle.net/a7q9k4uu/



                                      To make it more generic, the function could accept a predicate function with custom logic (returning true/false) which would determine the final count. For example:



                                      const dataset = [2,2,4,2,6,4,7,8];

                                      function getNumMatches(array, predicate) {
                                      let numMatches = 0;
                                      for (let i = 0, j = array.length; i < j; i += 1) {
                                      const current = array[i];
                                      if (predicate(current) === true) {
                                      numMatches += 1;
                                      }
                                      }
                                      return numMatches;
                                      }

                                      const numFound = getNumMatches(dataset, (item) => {
                                      return item === 2;
                                      });

                                      alert(numFound); // should alert 3


                                      DEMO: https://jsfiddle.net/57en9nar/1/






                                      share|improve this answer























                                      • +1 For wrapping in a semantically understandable and readable function. Although I would call it getNumMatches or getNumOccurrences. findOccurrences sounds like you're trying to return the occurrences themselves (an array) rather than how many of them there are (a number).
                                        – Adam Zerner
                                        Feb 23 at 17:52










                                      • Also, as others have mentioned, you can pass in a predicate function instead of a value to test for matches. Demo: repl.it/repls/DecimalFrostyTechnicians
                                        – Adam Zerner
                                        Feb 23 at 17:57










                                      • @AdamZerner Agreed, thanks for the input. Updated with your recommendations
                                        – Ian
                                        Feb 23 at 18:05













                                      up vote
                                      6
                                      down vote










                                      up vote
                                      6
                                      down vote









                                      Using a normal loop, you can find the occurrences consistently and reliably:



                                      const dataset = [2,2,4,2,6,4,7,8];

                                      function getNumMatches(array, valToFind) {
                                      let numMatches = 0;
                                      for (let i = 0, j = array.length; i < j; i += 1) {
                                      if (array[i] === valToFind) {
                                      numMatches += 1;
                                      }
                                      }
                                      return numMatches;
                                      }

                                      alert(getNumMatches(dataset, 2)); // should alert 3


                                      DEMO: https://jsfiddle.net/a7q9k4uu/



                                      To make it more generic, the function could accept a predicate function with custom logic (returning true/false) which would determine the final count. For example:



                                      const dataset = [2,2,4,2,6,4,7,8];

                                      function getNumMatches(array, predicate) {
                                      let numMatches = 0;
                                      for (let i = 0, j = array.length; i < j; i += 1) {
                                      const current = array[i];
                                      if (predicate(current) === true) {
                                      numMatches += 1;
                                      }
                                      }
                                      return numMatches;
                                      }

                                      const numFound = getNumMatches(dataset, (item) => {
                                      return item === 2;
                                      });

                                      alert(numFound); // should alert 3


                                      DEMO: https://jsfiddle.net/57en9nar/1/






                                      share|improve this answer














                                      Using a normal loop, you can find the occurrences consistently and reliably:



                                      const dataset = [2,2,4,2,6,4,7,8];

                                      function getNumMatches(array, valToFind) {
                                      let numMatches = 0;
                                      for (let i = 0, j = array.length; i < j; i += 1) {
                                      if (array[i] === valToFind) {
                                      numMatches += 1;
                                      }
                                      }
                                      return numMatches;
                                      }

                                      alert(getNumMatches(dataset, 2)); // should alert 3


                                      DEMO: https://jsfiddle.net/a7q9k4uu/



                                      To make it more generic, the function could accept a predicate function with custom logic (returning true/false) which would determine the final count. For example:



                                      const dataset = [2,2,4,2,6,4,7,8];

                                      function getNumMatches(array, predicate) {
                                      let numMatches = 0;
                                      for (let i = 0, j = array.length; i < j; i += 1) {
                                      const current = array[i];
                                      if (predicate(current) === true) {
                                      numMatches += 1;
                                      }
                                      }
                                      return numMatches;
                                      }

                                      const numFound = getNumMatches(dataset, (item) => {
                                      return item === 2;
                                      });

                                      alert(numFound); // should alert 3


                                      DEMO: https://jsfiddle.net/57en9nar/1/







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Feb 23 at 18:05

























                                      answered Jun 26 '13 at 6:55









                                      Ian

                                      39.2k118097




                                      39.2k118097












                                      • +1 For wrapping in a semantically understandable and readable function. Although I would call it getNumMatches or getNumOccurrences. findOccurrences sounds like you're trying to return the occurrences themselves (an array) rather than how many of them there are (a number).
                                        – Adam Zerner
                                        Feb 23 at 17:52










                                      • Also, as others have mentioned, you can pass in a predicate function instead of a value to test for matches. Demo: repl.it/repls/DecimalFrostyTechnicians
                                        – Adam Zerner
                                        Feb 23 at 17:57










                                      • @AdamZerner Agreed, thanks for the input. Updated with your recommendations
                                        – Ian
                                        Feb 23 at 18:05


















                                      • +1 For wrapping in a semantically understandable and readable function. Although I would call it getNumMatches or getNumOccurrences. findOccurrences sounds like you're trying to return the occurrences themselves (an array) rather than how many of them there are (a number).
                                        – Adam Zerner
                                        Feb 23 at 17:52










                                      • Also, as others have mentioned, you can pass in a predicate function instead of a value to test for matches. Demo: repl.it/repls/DecimalFrostyTechnicians
                                        – Adam Zerner
                                        Feb 23 at 17:57










                                      • @AdamZerner Agreed, thanks for the input. Updated with your recommendations
                                        – Ian
                                        Feb 23 at 18:05
















                                      +1 For wrapping in a semantically understandable and readable function. Although I would call it getNumMatches or getNumOccurrences. findOccurrences sounds like you're trying to return the occurrences themselves (an array) rather than how many of them there are (a number).
                                      – Adam Zerner
                                      Feb 23 at 17:52




                                      +1 For wrapping in a semantically understandable and readable function. Although I would call it getNumMatches or getNumOccurrences. findOccurrences sounds like you're trying to return the occurrences themselves (an array) rather than how many of them there are (a number).
                                      – Adam Zerner
                                      Feb 23 at 17:52












                                      Also, as others have mentioned, you can pass in a predicate function instead of a value to test for matches. Demo: repl.it/repls/DecimalFrostyTechnicians
                                      – Adam Zerner
                                      Feb 23 at 17:57




                                      Also, as others have mentioned, you can pass in a predicate function instead of a value to test for matches. Demo: repl.it/repls/DecimalFrostyTechnicians
                                      – Adam Zerner
                                      Feb 23 at 17:57












                                      @AdamZerner Agreed, thanks for the input. Updated with your recommendations
                                      – Ian
                                      Feb 23 at 18:05




                                      @AdamZerner Agreed, thanks for the input. Updated with your recommendations
                                      – Ian
                                      Feb 23 at 18:05










                                      up vote
                                      5
                                      down vote













                                      var dataset = [2,2,4,2,6,4,7,8], count = {}

                                      dataset.forEach(function(el){
                                      count[el] = count[el] + 1 || 1
                                      });

                                      console.log(count)

                                      // {
                                      // 2: 3,
                                      // 4: 2,
                                      // 6: 1,
                                      // 7: 1,
                                      // 8: 1
                                      // }





                                      share|improve this answer





















                                      • He checks on every loop if the key already exists. If yes increment the current value of the by one. If not insert 1 for this key.
                                        – TdoubleG
                                        Sep 28 '17 at 9:06

















                                      up vote
                                      5
                                      down vote













                                      var dataset = [2,2,4,2,6,4,7,8], count = {}

                                      dataset.forEach(function(el){
                                      count[el] = count[el] + 1 || 1
                                      });

                                      console.log(count)

                                      // {
                                      // 2: 3,
                                      // 4: 2,
                                      // 6: 1,
                                      // 7: 1,
                                      // 8: 1
                                      // }





                                      share|improve this answer





















                                      • He checks on every loop if the key already exists. If yes increment the current value of the by one. If not insert 1 for this key.
                                        – TdoubleG
                                        Sep 28 '17 at 9:06















                                      up vote
                                      5
                                      down vote










                                      up vote
                                      5
                                      down vote









                                      var dataset = [2,2,4,2,6,4,7,8], count = {}

                                      dataset.forEach(function(el){
                                      count[el] = count[el] + 1 || 1
                                      });

                                      console.log(count)

                                      // {
                                      // 2: 3,
                                      // 4: 2,
                                      // 6: 1,
                                      // 7: 1,
                                      // 8: 1
                                      // }





                                      share|improve this answer












                                      var dataset = [2,2,4,2,6,4,7,8], count = {}

                                      dataset.forEach(function(el){
                                      count[el] = count[el] + 1 || 1
                                      });

                                      console.log(count)

                                      // {
                                      // 2: 3,
                                      // 4: 2,
                                      // 6: 1,
                                      // 7: 1,
                                      // 8: 1
                                      // }






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Jan 4 '15 at 14:59









                                      Manolis

                                      47411128




                                      47411128












                                      • He checks on every loop if the key already exists. If yes increment the current value of the by one. If not insert 1 for this key.
                                        – TdoubleG
                                        Sep 28 '17 at 9:06




















                                      • He checks on every loop if the key already exists. If yes increment the current value of the by one. If not insert 1 for this key.
                                        – TdoubleG
                                        Sep 28 '17 at 9:06


















                                      He checks on every loop if the key already exists. If yes increment the current value of the by one. If not insert 1 for this key.
                                      – TdoubleG
                                      Sep 28 '17 at 9:06






                                      He checks on every loop if the key already exists. If yes increment the current value of the by one. If not insert 1 for this key.
                                      – TdoubleG
                                      Sep 28 '17 at 9:06












                                      up vote
                                      3
                                      down vote













                                      You can do with use of array.reduce(callback[, initialValue]) method in JavaScript 1.8



                                      var dataset = [2,2,4,2,6,4,7,8],
                                      dataWithCount = dataset.reduce( function( o , v ) {

                                      if ( ! o[ v ] ) {
                                      o[ v ] = 1 ;
                                      } else {
                                      o[ v ] = o[ v ] + 1;
                                      }

                                      return o ;

                                      }, {} );

                                      // print data with count.
                                      for( var i in dataWithCount ){
                                      console.log( i + 'occured ' + dataWithCount[i] + 'times ' );
                                      }

                                      // find one number
                                      var search = 2,
                                      count = dataWithCount[ search ] || 0;





                                      share|improve this answer



























                                        up vote
                                        3
                                        down vote













                                        You can do with use of array.reduce(callback[, initialValue]) method in JavaScript 1.8



                                        var dataset = [2,2,4,2,6,4,7,8],
                                        dataWithCount = dataset.reduce( function( o , v ) {

                                        if ( ! o[ v ] ) {
                                        o[ v ] = 1 ;
                                        } else {
                                        o[ v ] = o[ v ] + 1;
                                        }

                                        return o ;

                                        }, {} );

                                        // print data with count.
                                        for( var i in dataWithCount ){
                                        console.log( i + 'occured ' + dataWithCount[i] + 'times ' );
                                        }

                                        // find one number
                                        var search = 2,
                                        count = dataWithCount[ search ] || 0;





                                        share|improve this answer

























                                          up vote
                                          3
                                          down vote










                                          up vote
                                          3
                                          down vote









                                          You can do with use of array.reduce(callback[, initialValue]) method in JavaScript 1.8



                                          var dataset = [2,2,4,2,6,4,7,8],
                                          dataWithCount = dataset.reduce( function( o , v ) {

                                          if ( ! o[ v ] ) {
                                          o[ v ] = 1 ;
                                          } else {
                                          o[ v ] = o[ v ] + 1;
                                          }

                                          return o ;

                                          }, {} );

                                          // print data with count.
                                          for( var i in dataWithCount ){
                                          console.log( i + 'occured ' + dataWithCount[i] + 'times ' );
                                          }

                                          // find one number
                                          var search = 2,
                                          count = dataWithCount[ search ] || 0;





                                          share|improve this answer














                                          You can do with use of array.reduce(callback[, initialValue]) method in JavaScript 1.8



                                          var dataset = [2,2,4,2,6,4,7,8],
                                          dataWithCount = dataset.reduce( function( o , v ) {

                                          if ( ! o[ v ] ) {
                                          o[ v ] = 1 ;
                                          } else {
                                          o[ v ] = o[ v ] + 1;
                                          }

                                          return o ;

                                          }, {} );

                                          // print data with count.
                                          for( var i in dataWithCount ){
                                          console.log( i + 'occured ' + dataWithCount[i] + 'times ' );
                                          }

                                          // find one number
                                          var search = 2,
                                          count = dataWithCount[ search ] || 0;






                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited Jun 26 '13 at 9:47

























                                          answered Jun 26 '13 at 6:57









                                          rab

                                          3,14712338




                                          3,14712338






















                                              up vote
                                              2
                                              down vote













                                              You can count all items in an array, in a single line, using reduce.



                                              .reduce((a,b) => (a[b] = a[b] + 1 || 1) && a, {})


                                              This will yield an object, whose keys are the distinct elements in the array and values are the count of occurences of elements in the array. You can then access one or more of the counts by accessing a corresponding key on the object.



                                              For example if you were to wrap the above in a function called count():



                                              function count(arr) {
                                              return arr.reduce((a,b) => (a[b] = a[b] + 1 || 1) && a, {})
                                              }

                                              count(['example']) // { example: 1 }
                                              count([2,2,4,2,6,4,7,8])[2] // 3





                                              share|improve this answer

























                                                up vote
                                                2
                                                down vote













                                                You can count all items in an array, in a single line, using reduce.



                                                .reduce((a,b) => (a[b] = a[b] + 1 || 1) && a, {})


                                                This will yield an object, whose keys are the distinct elements in the array and values are the count of occurences of elements in the array. You can then access one or more of the counts by accessing a corresponding key on the object.



                                                For example if you were to wrap the above in a function called count():



                                                function count(arr) {
                                                return arr.reduce((a,b) => (a[b] = a[b] + 1 || 1) && a, {})
                                                }

                                                count(['example']) // { example: 1 }
                                                count([2,2,4,2,6,4,7,8])[2] // 3





                                                share|improve this answer























                                                  up vote
                                                  2
                                                  down vote










                                                  up vote
                                                  2
                                                  down vote









                                                  You can count all items in an array, in a single line, using reduce.



                                                  .reduce((a,b) => (a[b] = a[b] + 1 || 1) && a, {})


                                                  This will yield an object, whose keys are the distinct elements in the array and values are the count of occurences of elements in the array. You can then access one or more of the counts by accessing a corresponding key on the object.



                                                  For example if you were to wrap the above in a function called count():



                                                  function count(arr) {
                                                  return arr.reduce((a,b) => (a[b] = a[b] + 1 || 1) && a, {})
                                                  }

                                                  count(['example']) // { example: 1 }
                                                  count([2,2,4,2,6,4,7,8])[2] // 3





                                                  share|improve this answer












                                                  You can count all items in an array, in a single line, using reduce.



                                                  .reduce((a,b) => (a[b] = a[b] + 1 || 1) && a, {})


                                                  This will yield an object, whose keys are the distinct elements in the array and values are the count of occurences of elements in the array. You can then access one or more of the counts by accessing a corresponding key on the object.



                                                  For example if you were to wrap the above in a function called count():



                                                  function count(arr) {
                                                  return arr.reduce((a,b) => (a[b] = a[b] + 1 || 1) && a, {})
                                                  }

                                                  count(['example']) // { example: 1 }
                                                  count([2,2,4,2,6,4,7,8])[2] // 3






                                                  share|improve this answer












                                                  share|improve this answer



                                                  share|improve this answer










                                                  answered Jul 28 '17 at 21:25









                                                  justin.m.chase

                                                  7,72853270




                                                  7,72853270






















                                                      up vote
                                                      0
                                                      down vote













                                                      I've found it more useful to end up with a list of objects with a key for what is being counted and a key for the count:



                                                      const data = [2,2,4,2,6,4,7,8]
                                                      let counted =
                                                      for (var c of data) {
                                                      const alreadyCounted = counted.map(c => c.name)
                                                      if (alreadyCounted.includes(c)) {
                                                      counted[alreadyCounted.indexOf(c)].count += 1
                                                      } else {
                                                      counted.push({ 'name': c, 'count': 1})
                                                      }
                                                      }
                                                      console.log(counted)


                                                      which returns:



                                                      [ { name: 2, count: 3 },
                                                      { name: 4, count: 2 },
                                                      { name: 6, count: 1 },
                                                      { name: 7, count: 1 },
                                                      { name: 8, count: 1 } ]


                                                      It isn't the cleanest method, and if anyone knows how to achieve the same result with reduce let me know. However, it does produce a result that's fairly easy to work with.






                                                      share|improve this answer

























                                                        up vote
                                                        0
                                                        down vote













                                                        I've found it more useful to end up with a list of objects with a key for what is being counted and a key for the count:



                                                        const data = [2,2,4,2,6,4,7,8]
                                                        let counted =
                                                        for (var c of data) {
                                                        const alreadyCounted = counted.map(c => c.name)
                                                        if (alreadyCounted.includes(c)) {
                                                        counted[alreadyCounted.indexOf(c)].count += 1
                                                        } else {
                                                        counted.push({ 'name': c, 'count': 1})
                                                        }
                                                        }
                                                        console.log(counted)


                                                        which returns:



                                                        [ { name: 2, count: 3 },
                                                        { name: 4, count: 2 },
                                                        { name: 6, count: 1 },
                                                        { name: 7, count: 1 },
                                                        { name: 8, count: 1 } ]


                                                        It isn't the cleanest method, and if anyone knows how to achieve the same result with reduce let me know. However, it does produce a result that's fairly easy to work with.






                                                        share|improve this answer























                                                          up vote
                                                          0
                                                          down vote










                                                          up vote
                                                          0
                                                          down vote









                                                          I've found it more useful to end up with a list of objects with a key for what is being counted and a key for the count:



                                                          const data = [2,2,4,2,6,4,7,8]
                                                          let counted =
                                                          for (var c of data) {
                                                          const alreadyCounted = counted.map(c => c.name)
                                                          if (alreadyCounted.includes(c)) {
                                                          counted[alreadyCounted.indexOf(c)].count += 1
                                                          } else {
                                                          counted.push({ 'name': c, 'count': 1})
                                                          }
                                                          }
                                                          console.log(counted)


                                                          which returns:



                                                          [ { name: 2, count: 3 },
                                                          { name: 4, count: 2 },
                                                          { name: 6, count: 1 },
                                                          { name: 7, count: 1 },
                                                          { name: 8, count: 1 } ]


                                                          It isn't the cleanest method, and if anyone knows how to achieve the same result with reduce let me know. However, it does produce a result that's fairly easy to work with.






                                                          share|improve this answer












                                                          I've found it more useful to end up with a list of objects with a key for what is being counted and a key for the count:



                                                          const data = [2,2,4,2,6,4,7,8]
                                                          let counted =
                                                          for (var c of data) {
                                                          const alreadyCounted = counted.map(c => c.name)
                                                          if (alreadyCounted.includes(c)) {
                                                          counted[alreadyCounted.indexOf(c)].count += 1
                                                          } else {
                                                          counted.push({ 'name': c, 'count': 1})
                                                          }
                                                          }
                                                          console.log(counted)


                                                          which returns:



                                                          [ { name: 2, count: 3 },
                                                          { name: 4, count: 2 },
                                                          { name: 6, count: 1 },
                                                          { name: 7, count: 1 },
                                                          { name: 8, count: 1 } ]


                                                          It isn't the cleanest method, and if anyone knows how to achieve the same result with reduce let me know. However, it does produce a result that's fairly easy to work with.







                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Feb 8 at 14:38









                                                          crash springfield

                                                          1933520




                                                          1933520






















                                                              up vote
                                                              0
                                                              down vote













                                                              First, you can go with Brute Force Solution by going with Linear Search.



                                                              public int LinearSearchcount(int A, int data){
                                                              int count=0;
                                                              for(int i=0;i<A.length;i++) {
                                                              if(A[i]==data) count++;
                                                              }
                                                              return count;
                                                              }


                                                              However, for going with this, we get Time complexity as O(n).But by going with Binary search, we can improve our Complexity.






                                                              share|improve this answer



























                                                                up vote
                                                                0
                                                                down vote













                                                                First, you can go with Brute Force Solution by going with Linear Search.



                                                                public int LinearSearchcount(int A, int data){
                                                                int count=0;
                                                                for(int i=0;i<A.length;i++) {
                                                                if(A[i]==data) count++;
                                                                }
                                                                return count;
                                                                }


                                                                However, for going with this, we get Time complexity as O(n).But by going with Binary search, we can improve our Complexity.






                                                                share|improve this answer

























                                                                  up vote
                                                                  0
                                                                  down vote










                                                                  up vote
                                                                  0
                                                                  down vote









                                                                  First, you can go with Brute Force Solution by going with Linear Search.



                                                                  public int LinearSearchcount(int A, int data){
                                                                  int count=0;
                                                                  for(int i=0;i<A.length;i++) {
                                                                  if(A[i]==data) count++;
                                                                  }
                                                                  return count;
                                                                  }


                                                                  However, for going with this, we get Time complexity as O(n).But by going with Binary search, we can improve our Complexity.






                                                                  share|improve this answer














                                                                  First, you can go with Brute Force Solution by going with Linear Search.



                                                                  public int LinearSearchcount(int A, int data){
                                                                  int count=0;
                                                                  for(int i=0;i<A.length;i++) {
                                                                  if(A[i]==data) count++;
                                                                  }
                                                                  return count;
                                                                  }


                                                                  However, for going with this, we get Time complexity as O(n).But by going with Binary search, we can improve our Complexity.







                                                                  share|improve this answer














                                                                  share|improve this answer



                                                                  share|improve this answer








                                                                  edited May 10 at 9:05









                                                                  coudy.one

                                                                  875721




                                                                  875721










                                                                  answered May 10 at 8:41









                                                                  Balaji Mj

                                                                  15




                                                                  15






























                                                                      draft saved

                                                                      draft discarded




















































                                                                      Thanks for contributing an answer to Stack Overflow!


                                                                      • Please be sure to answer the question. Provide details and share your research!

                                                                      But avoid



                                                                      • Asking for help, clarification, or responding to other answers.

                                                                      • Making statements based on opinion; back them up with references or personal experience.


                                                                      To learn more, see our tips on writing great answers.





                                                                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                                                      Please pay close attention to the following guidance:


                                                                      • Please be sure to answer the question. Provide details and share your research!

                                                                      But avoid



                                                                      • Asking for help, clarification, or responding to other answers.

                                                                      • Making statements based on opinion; back them up with references or personal experience.


                                                                      To learn more, see our tips on writing great answers.




                                                                      draft saved


                                                                      draft discarded














                                                                      StackExchange.ready(
                                                                      function () {
                                                                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f17313268%2fidiomatically-find-the-number-of-occurrences-a-given-value-has-in-an-array%23new-answer', 'question_page');
                                                                      }
                                                                      );

                                                                      Post as a guest















                                                                      Required, but never shown





















































                                                                      Required, but never shown














                                                                      Required, but never shown












                                                                      Required, but never shown







                                                                      Required, but never shown

































                                                                      Required, but never shown














                                                                      Required, but never shown












                                                                      Required, but never shown







                                                                      Required, but never shown







                                                                      Popular posts from this blog

                                                                      Guess what letter conforming each word

                                                                      Port of Spain

                                                                      Run scheduled task as local user group (not BUILTIN)