Find your people. Pick a challenge. Ship something real. The CreatorCon Hackathon is coming to the Community Pavilion for one epic night. Every skill level, every role welcome. Join us on May 5th and learn more here.

How to check a value is included in array or not.

roshini1
Kilo Guru

am getting 'return JSON.stringify(CIs)' value as ["CI1","CI2","CI3","CI14"] form script include, I need to check the selected ci (eg:- CI1) on the form is part of this return value or not.
if yes need to give an alert
can i know how to achieve this. 
Am able to get the values from script include to client script, but am struggling with the conditional check.

1 ACCEPTED SOLUTION

palanikumar
Giga Sage

You can use indexOf function to check whether a value is present in the array of not. -1 refers value not present

Refer sample script

var ciArr = ["CI1","CI2","CI3","CI14"];

gs.info(ciArr.indexOf("CI1")); // Returns 0
gs.info(ciArr.indexOf("CI3")); // Returns 2
gs.info(ciArr.indexOf("CI5")); // Returns -1
gs.info(ciArr.indexOf("CI")); // Returns -1


Thank you,
Palani

View solution in original post

3 REPLIES 3

palanikumar
Giga Sage

You can use indexOf function to check whether a value is present in the array of not. -1 refers value not present

Refer sample script

var ciArr = ["CI1","CI2","CI3","CI14"];

gs.info(ciArr.indexOf("CI1")); // Returns 0
gs.info(ciArr.indexOf("CI3")); // Returns 2
gs.info(ciArr.indexOf("CI5")); // Returns -1
gs.info(ciArr.indexOf("CI")); // Returns -1


Thank you,
Palani

SumanthDosapati
Mega Sage

Hi Roshini,

As you are passing it as JSON string then try below.

var returnedValue; //store returned value in this variable
if(returnedValue.includes(g_form.getValue('ci_field_name')))
{
alert("yes");
}
else
{
alert("no");
}

 

Mark as correct and helpful if it solved your query.

Regards,
Sumanth

 

Shubham1195
Tera Contributor

I was always getting  false value while using array.includes() directly to compare multiple string values in a single time.
To overcome this issue you should use 
var str = array.toString();
str.includes("CI1") && str.includes("CI2") ? return true : return false;