Convert array with duplicate values to object with number of repeated occurrences in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an array string that contains some duplicate entries like this −

const arr = ['California','Texas','Texas','Texas','New
York','Missouri','New Mexico','California'];

We are required to write a JavaScript function that takes in one such array. Our function should then construct an array of objects that contains an object for each unique entry and a property "count" that contains its count in the original array.

Therefore, the final output for the above array should look something like this −

const output = [
   {'name':'California', 'count':2},
   {'name':'Texas', 'count':3},
   {'name':'New York', 'count':1},
   {'name':'Missouri', 'count':1},
   {'name':'New Mexico', 'count':1},
];

Example

The code for this will be −

const arr = ['California','Texas','Texas','Texas','New York','Missouri','New Mexico','California'];
const findOccurrences = (arr = []) => {
   const res = [];
   arr.forEach(el => {
      const index = res.findIndex(obj => {
         return obj['name'] === el;
      });
      if(index === -1){
         res.push({
            "name": el,
            "count": 1
         })
      }
      else{
         res[index]["count"]++;
      };
   });
   return res;
};
console.log(findOccurrences(arr));

Output

And the output in the console will be −

[
   { name: 'California', count: 2 },
   { name: 'Texas', count: 3 },
   { name: 'New York', count: 1 },
   { name: 'Missouri', count: 1 },
   { name: 'New Mexico', count: 1 }
]
raja
Published on 23-Nov-2020 10:04:23
Advertisements