- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-24-2020 10:30 PM
Hi,
How to find the count of duplicated array values and list it in key-value pair object.
for example : having array of {a,b,a,c,b,a}
the result would be [{"group":"a","score":"3"},{"group":"b","score":"2"},{"group":"c","score":"1"}]
Can anyone help please?
Thanks in advance!
Solved! Go to Solution.
- Labels:
-
Service Catalog

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-24-2020 11:17 PM
Hi ,
Here is function that will count each type of duplicate element.
function count() {
array_elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
array_elements.sort();
var current = null;
var cnt = 0;
for (var i = 0; i < array_elements.length; i++) {
if (array_elements[i] != current) {
if (cnt > 0) {
document.write(current + ' comes --> ' + cnt + ' times<br>');
}
current = array_elements[i];
cnt = 1;
} else {
cnt++;
}
}
if (cnt > 0) {
document.write(current + ' comes --> ' + cnt + ' times');
}
}
Output
a comes --> 3 times
b comes --> 2 times
c comes --> 2 times
d comes --> 1 times
e comes --> 2 times
f comes --> 1 times
g comes --> 1 times
h comes --> 3 times
If it helps,Please mark ✅ Correct and 👍 Helpful.
Warm Regards,
Milind

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-24-2020 10:49 PM
Hi Fatima ,
For this you have to iterate throw the array and take count of each array element,
var final=[];
for(var i=0.i<array.length,i++)
{
var temp=array[i];
var count=0;
for(var j=i+1;j<array.length,i++)
{
if(array[i]==array[j])
count=count+1;
}
final.push({"group":"array[i]","score":"count"});
}
Please mark if that helps You in any way!!!

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-24-2020 11:17 PM
Hi ,
Here is function that will count each type of duplicate element.
function count() {
array_elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
array_elements.sort();
var current = null;
var cnt = 0;
for (var i = 0; i < array_elements.length; i++) {
if (array_elements[i] != current) {
if (cnt > 0) {
document.write(current + ' comes --> ' + cnt + ' times<br>');
}
current = array_elements[i];
cnt = 1;
} else {
cnt++;
}
}
if (cnt > 0) {
document.write(current + ' comes --> ' + cnt + ' times');
}
}
Output
a comes --> 3 times
b comes --> 2 times
c comes --> 2 times
d comes --> 1 times
e comes --> 2 times
f comes --> 1 times
g comes --> 1 times
h comes --> 3 times
If it helps,Please mark ✅ Correct and 👍 Helpful.
Warm Regards,
Milind