The CreatorCon Call for Content is officially open! Get started here.

Need help in scripting to push unique values in array

shaik_irfan
Tera Guru

Hi,

 

I have a script which is on inbound action that takes the subject and search for a keyword and get the knowledge article number and push into an array. Which is working fine

 

But if in case i have duplicate keywords then it is pushing the kb number multiple times. how to push only unique number

 

var arr = [];
var substring = email.subject;
substring = substring.split(" ");

for(var i=0; i<substring.length; i++){

if(substring[i] != " "){

var kn = new GlideRecord('kb_knowledge');
kn.addEncodedQuery('metaLIKE'+substring[i]);
kn.query();
if(kn.next()){
	gs.log('Found kb');
	checked = 'true';
	
	var url = '/sp?id=kb_article&sys_id=' + kn.sys_id;
	var com = '[code]<a href="' + url + '" target="_blank" >' + gs.getMessage(kn.number) + '</a>[/code]';
	com += "\n";
	arr.push(com);
}

	

	}
}

 

If i send the subject as "I have issue with my computer" then i get one article like KB0000002

 

If i send the subject as "My Computer is not working, i already troubleshooted my computer" then i get result in my array as KB0000002, KB0000002

 

Since i found the Computer keyword twice i get kb number twice but i want to display only once

 

Can anyone please help me how to do this

1 ACCEPTED SOLUTION

Mwatkins
ServiceNow Employee
ServiceNow Employee

 

Hm... you want to avoid the same KB twice, right? So you need the unique check on the "arr" array to see if a given KB is already in it. I think I'd do it like this:

if (arr.indexOf(kn.number) == -1)
arr.push('[code]<a href="' + url + '" target="_blank" >' + gs.getMessage(kn.number) + '</a>[/code]');

 

View solution in original post

8 REPLIES 8

Thanks Muhammad for the catch.

Updated the script. Happens many times when we don't test the code at our end & provide a solution.

Yeah, Agree :')

Regards,
Muhammad

Mwatkins
ServiceNow Employee
ServiceNow Employee

 

Hm... you want to avoid the same KB twice, right? So you need the unique check on the "arr" array to see if a given KB is already in it. I think I'd do it like this:

if (arr.indexOf(kn.number) == -1)
arr.push('[code]<a href="' + url + '" target="_blank" >' + gs.getMessage(kn.number) + '</a>[/code]');

 

@Mwatkins 

 

A slight change made the trick

 

if (arr.toString().indexOf(kn.number) == -1)