Nodejs Array Item Occurrence numberOfOccurrences( arg )

Here you can find the source of numberOfOccurrences( arg )

Method Source Code

// The numberOfOccurrences function must return the number of occurrences of an element in an array.

// var arr = [0,1,2,2,3];
// arr.numberOfOccurrences(0) === 1;
// arr.numberOfOccurrences(4) === 0;
// arr.numberOfOccurrences(2) === 2;
// arr.numberOfOccurrences("a") === 0;

Array.prototype.numberOfOccurrences = function( arg ) {
  var num = 0;/*from  w  w  w.j  av a2  s . c  om*/
  this.forEach( function( e ){
    if ( arg === e ) { num++; }
  });
  return num;
};

var arr = [0,1,2,2,3,"a"];

console.log( arr.numberOfOccurrences("a") );

Related

  1. numberOfOccurrences(arr)
    Array.prototype.numberOfOccurrences = function (arr) {
        var elem = 0;
        for (var i = 0; i < this.length; i++) {
            if (this[i] === arr) {
                elem++;
        return elem;
    };
    ...
    
  2. numberOfOccurrences(chr)
    Array.prototype.numberOfOccurrences = function(chr) {
      return this.filter(function(x){ return x == chr; }).length;
    
  3. numberOfOccurrences(desVal)
    Array.prototype.numberOfOccurrences = function(desVal) {
      var counter = 0;
      this.forEach(function(value){
        if(value === desVal){
          counter++;
      });
      return counter;
    };
    ...
    
  4. numberOfOccurrences(el)
    Array.prototype.numberOfOccurrences = function (el) {
      var count = 0;
      this.forEach(function (item) {
        if (item === el) count++;
      });
      return count;