How do you count occurrences of an object in a javascript array, then associate this with the object. For example: 
If my array is : [4,5,5,4,5,3,3,5,4,3]
How would I get a key/value pair that would count how many times the object occurred, and what object that is. So the output I am looking for is: {3:3, 4:3, 5:4} meaning 3 occurred 3 times, 4 occurred 3 times, and 5 occurred 4 times.
            Asked
            
        
        
            Active
            
        
            Viewed 782 times
        
    1
            
            
         
    
    
        MattG
        
- 1,682
- 5
- 25
- 45
- 
                    3Have you searched the archives for this? There are many existing answers. (i.e. https://stackoverflow.com/questions/5667888/counting-the-occurrences-frequency-of-array-elements) – Mark Feb 04 '19 at 21:34
2 Answers
3
            You can accomplish this succintly using reduce:
const input = [4,5,5,4,5,3,3,5,4,3];
const output = input.reduce((accum, x) => {
  accum[x] = accum[x] ? accum[x] + 1 : 1;
  return accum;
}, {});
console.log(output); 
    
    
        jo_va
        
- 13,504
- 3
- 23
- 47
2
            
            
        You can use Array.prototype.reduce() to iterate through the array. The accumulator in the function will be a plain object, {}, and in each iteration you simply check if the array's item is a key in the object or not:
- if it is not, then create a new key and give it a count of 1
- if it is, then access the pre-existing key and increment its count by 1
const arr = [4,5,5,4,5,3,3,5,4,3];
const keyedArr = arr.reduce((accumulator, currentValue) => {
  const key = currentValue.toString();
  if (!(key in accumulator))
    accumulator[key] = 1;
  else
    accumulator[key] += 1;
    
  return accumulator;
}, {});
console.log(keyedArr); 
    
    
        Terry
        
- 63,248
- 15
- 96
- 118