Reputation: 5485
I had a requirement, like:
Given an array, having random numbers. Need to output the number of occurrences of the elements, Have Come with with the solution :
var myArr = [3,2,1,2,3,1,4,5,4,6,7,7,9,1,123,0,123];
Array.prototype.showOccurences= function(){
this.sort();
var sorted={}, sortArr=[];
for(var i=0; i<this.length; i++){
if(this[i] === this[i + 1]){
sortArr.push(this[i]);
sorted[this[i]]= sortArr.length + 1;
}else{
sortArr=[];
if(sorted[this[i]] === undefined){
sorted[this[i]] = 1;
}
}
}
return sorted;
}
console.log(myArr);
console.log(myArr.showOccurences());
Fiddle What I want here, 1. Is this can be improved with a Better solution, using some kind of algorithms like hashmap
Upvotes: 1
Views: 36
Reputation: 66663
A shorter version of the same:
Array.prototype.showOccurences= function(){
var c=[];
for(var i=0; i<this.length; i++)
c[this[i]] = (!c[this[i]]) ? 1 : c[this[i]]+1;
return c;
}
Update fiddle: http://jsfiddle.net/afzLD/2/
Upvotes: 2