How to fetch array if it contains particular string?

Gayathri5
Tera Guru

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

 

17 REPLIES 17

Kartik Sethi
Tera Guru
Tera Guru

Hi @Gayathri 

 

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:

find_real_file.png

 


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

Hi @Gayathri 

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

Ed13
Tera Contributor

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 @Nick Parsons  answer, you should not use (for .. in) on arrays, it is designed for objects. 

 

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!