Thinking about a js algorithm, how to calculate the number of occurrences of all items in an array

 var arr = [1, 2, 3, 1, 5, 8, 2, 9, 9, 2, 2, 2, 3];



:  
:1, 2, 3, 5, 8, 9
122532518192



~~~
Jan.08,2022

initialize the empty object, traverse the array, set the array member to the key of the object, initially value to 0, and then each key PP

var ret = arr.reduce(function(obj,val){    
    if(obj[val] != undefined){
        obj[val] = obj[val] + 1;
    }else{
        obj[val] = 1;
    }
    return obj;
},{});
Menu