Home > OS >  Loop breaks over an array when a condition is met with google apps script
Loop breaks over an array when a condition is met with google apps script

Time:12-05

I have an array and I am trying to identify a particular text in every element and remove only if that element from the array where there is a match.

the array is

var Concat_names = ['Prod 1-Volume based deal-100 sections','Test Prod 1-Included Members-MB,'Prod 2-Commitment   Excess-100 sections','Prod 1-Flat Mon-TB'];
  1. If any element in the array has Flat Mon then remove that element from array
  2. If any element in the array has Included Members then remove that element from array

The below is what I tried-

for (var i in Concat_names) {
    var check_included_mem = Concat_names[i].includes("Included Members");
    if (check_included_mem == true) {
      Concat_names.splice(i);
    }
  }
  console.log(Concat_names);

for (var y in Concat_names){
    var check_flat_mon = new RegExp(/Flat Mon/).test(Concat_names[y]); 
    if (check_flat_mon==true){
      Concat_names.splice(y);
    }
  }
  console.log(Concat_names);

With the above code, the loop is breaking out whenever the condition is met and missing out on other elements in the array.

The output I am getting is

[ 'Prod 1-Volume based deal-100 sections' ] 

whereas the output should be

['Prod 1-Volume based deal-100 sections','Prod 2-Commitment   Excess-100 sections']

Please guide and help!

CodePudding user response:

In your script, how about the following modification?

From:

Concat_names.splice(i);

To:

Concat_names.splice(i, 1);

In this case, please modify both Concat_names.splice(i); to Concat_names.splice(i, 1);.

Testing:

var Concat_names = ['Prod 1-Volume based deal-100 sections', 'Test Prod 1-Included Members-MB', 'Prod 2 - Commitment   Excess - 100 sections', 'Prod 1 - Flat Mon - TB'];

for (var i in Concat_names) {
  var check_included_mem = Concat_names[i].includes("Included Members");
  if (check_included_mem == true) {
    Concat_names.splice(i, 1);
  }
}
console.log(Concat_names);
for (var y in Concat_names) {
  var check_flat_mon = new RegExp(/Flat Mon/).test(Concat_names[y]);
  if (check_flat_mon == true) {
    Concat_names.splice(y, 1);
  }
}
console.log(Concat_names);

Note:

  • In your situation, the following script might be able to be also used.

var Concat_names = ['Prod 1-Volume based deal-100 sections', 'Test Prod 1-Included Members-MB', 'Prod 2 - Commitment   Excess - 100 sections', 'Prod 1 - Flat Mon - TB'];
var res = Concat_names.filter(e => !["Included Members", "Flat Mon"].some(f => e.includes(f)));
console.log(res)

Reference:

  • Related