I have an array of positive integers. Some are unique and some are duplicates. I'm trying to make a function that will count the number of duplicates and pair it with the relevant number.
For instance, if I had this array to start with:
arr = [89, 1, 1, 2, 89, 89];
I'm trying to get this as the result:
res = [
{"id" : 1, "count" : 2 },
{"id" : 2, "count" : 1 },
{"id" : 89, "count" : 3 }
];
This is the function I made up but it doesn't work and I feel like there's a better solution:
function cons_dupes(arr) {
//Consolidate duplicates by deleting everything but one of each.
//Also adds a count of total duplicates with each index.
var out = {};
for (i=0;i<arr.length;i++)
{
if (arr[i] !== 'null')
{
out[i] = {
data: arr[i],
count: 1
};
for (ii=0; ii<arr.length; ii++)
{
if (arr[i]==arr[ii])
{
arr[ii] = 'null';
out[i].count++;
}
}
}
else
{
console.log('null value: arr['+ii+']');
}
}
return out;
}
Any help is greatly appreciated!