Javascript Array numberOfOccurrences(item)

Description

Javascript Array numberOfOccurrences(item)


/*//from   w  w w  .  j  a  v  a  2  s.  c  om
# Codewars: Number of Occurrences

In this exercise, we are asked to check the occurrence of an array item.

*/

var arr = [4, 0, 4];

Array.prototype.numberOfOccurrences = function(item) {

 tmp = 0;

 for(var i=0; i<this.length; i++){
  if (item == this[i]) {
   tmp ++;
  }
 }

 // return tmp;
 console.log(tmp);

}

arr.numberOfOccurrences(0);
arr.numberOfOccurrences(4);
arr.numberOfOccurrences("a");

Javascript Array numberOfOccurrences(item)

// http://www.codewars.com/kata/number-of-occurrences/javascript

Array.prototype.numberOfOccurrences = function(item) {
var drr = []; // Empty array
var i = 0 ;/*www . j  a  va2s . c  om*/
   for(i = 0 ; i < this.length ; i++) {
       if(item=== this[i]){
         drr.push(this[i]); // looping through the item and pushing the same number of occurrences into the empty array.
       }
   }
    return drr.length;

}



PreviousNext

Related