Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert array with duplicate values to object with number of repeated occurrences in JavaScript
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 }
]Advertisements