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
asked May 9, 2014 at 4:06
RONE
5,5059 gold badges45 silver badges78 bronze badges
1 Answer 1
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/
answered May 9, 2014 at 4:13
techfoobar
66.8k14 gold badges117 silver badges138 bronze badges
Sign up to request clarification or add additional context in comments.
6 Comments
techfoobar
@JoãoMosmann - Sorting isn't really needed to get the counts.
João Mosmann
Yes, but the output is different from the original script. The original outputted the array sorted by the number of occurrences.
RONE
@techfoobar, hey, i went through your blog, great posting, I need a favour, can you point out the lines/code which is not of useful, In my code implementation.So as to improve my coding standards
techfoobar
@SAM - In your code, you are using a purely logical approach to solving using traditional array handling (like you would do in C). But in JavaScript arrays are slightly different in that the keys can be anything, not necessarily a linear range starting from 0 (though by default it is). This is essentially what you can see in the solution. And as such we do not need to even sort the array for getting the counts.
techfoobar
@SAM - Secondly, adding that method to the Array's prototype will add it to all array instances. For example, even in the array that holds the counts (which is fine, if this behavior is desired).
|
lang-js