简体   繁体   中英

Better solution / improvement required

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM