How to fetch array if it contains particular string?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-17-2022 09:29 PM
Hi All,
I have array it contains
var allarr =[];
var incarr =[];
allarr=INCXXXX, INCXXXX, PRBXXXX, SCTXXXXX, PRBXXXX;
now i am checking if allarr contains INC separate it in another array which is not working
for(var x in allarr){
gs.log("Inside for loop:"+allarr);//going here
if(allarr[x].indexof('INC') > -1){
incarr.push(allarr[x]);
gs.log("Inside if:"+incarr); //not going inside if loop
}
}
after going inside if loop i want to separate all incidents in one array, can any one help me pls
Regards,
Gayathri
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-17-2022 10:22 PM
Hi
You can try the below-provided code:
var allArr =[],
incArr =[];
allArr=['INC00001', 'INC00002', 'PRB00001', 'SCT00001', 'PRB00002', 'INC00003'];
//Populating the incArr separately
for(var i = 0; i < allArr.length; i ++) {
if(allArr[i].indexOf('INC') > -1) {
incArr.push(allArr[i]);
}
}
//Cleaning the allArr array
allArr = recursiveSplice(allArr);
function recursiveSplice(arr) {
for(var i = 0; i < arr.length; i++) {
if(arr[i].indexOf('INC') > -1) {
arr.splice(i,1);
recursiveSplice(arr);
break;
}
}
return arr;
}
gs.inf0('IncArr: ' + incArr);
gs.info('AllArr: ' + allArr);
With the above code, you can separate the arrays with the required results.
Results from browser console:
Please mark my answer as correct if this solves your issues!
If it helped you in any way then please mark helpful!
Thanks and regards,
Kartik
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-19-2022 11:27 PM
Hi
Is your issue resolved?
If yes and if my answer helped you out then please mark my answer as correct/helpful, so that other community members facing similar issues might get help.
Thanks and regards,
Kartik
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-31-2022 02:39 AM
Or a simple 'if / else' should do the trick :
var allArr=['INC51321', 'INC580131', 'PRB651651', 'SCT651651', 'INC651321']
var incArr =[];
var restArr = [];
for (i=0; i < allArr.length; i++) {
if (allArr[i].startsWith('INC')) {
incArr.push(allArr[i]);
} else {
restArr.push(allArr[i]);
}
}
gs.info(incArr) //Output ['INC51321', 'INC580131', 'INC651321']
gs.info(restArr) // Output ['PRB651651', 'SCT651651']
You should also check
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
Thank You,
Ed`N
Mark the answer as correct if this solves the issue
If it helped you in any way then please mark helpful!