1

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

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

6 Comments

@JoãoMosmann - Sorting isn't really needed to get the counts.
Yes, but the output is different from the original script. The original outputted the array sorted by the number of occurrences.
@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
@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.
@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).
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.