Javascript Array numberOfOccurrences( arg )

Description

Javascript Array numberOfOccurrences( arg )


// 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  .  ja  v a  2 s.  co m
  this.forEach( function( e ){
    if ( arg === e ) { num++; }
  });
  return num;
};

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

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



PreviousNext

Related