We've updated the ServiceNow Community Code of Conduct, adding guidelines around AI usage, professionalism, and content violations. Read more

How to find the count of duplicated array values and list it in key-value pair object.

Fathima6
Tera Expert

 

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!

1 ACCEPTED SOLUTION

Milind Gharte
Kilo Guru

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

 

View solution in original post

2 REPLIES 2

Priya Shid1
Kilo Guru

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!!!

Milind Gharte
Kilo Guru

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