Home > database >  Google apps script loop mises an iteration
Google apps script loop mises an iteration

Time:01-12

I have an array I am trying to remove entry if a particular string is found The code is skipping an entry in the loop to check

unction test(){
  var Concat_names = ["Test 1-Coms-2A Up", "Test 1-Included Units-10G", "test 2-Included Units-1000 Sa", "test 2-Percentage-MB"];
  for (var i in Concat_names) {
    console.log(Concat_names[i]);
    var check_included_units = Concat_names[i].includes("Included Units");
    console.log(check_included_units)
    if (check_included_units == true) {
      Concat_names.splice(i,1);
    }
    else if (check_included_units == false){
      continue;
    }
  }
  console.log(Concat_names);
}

The output is as below-

enter image description here

Please suggest what is wrong here and how to fix

CodePudding user response:

In your script, when Concat_names.splice(i, 1) is run, Concat_names is changed. By this, i is changed. I think that this might be the reason for your current issue. In this case, how about looping from the last element? When this is reflected in your showing script, how about the following modification?

Modified script:

var Concat_names = ["Test 1-Coms-2A Up", "Test 1-Included Units-10G", "test 2-Included Units-1000 Sa", "test 2-Percentage-MB"];
for (var i = Concat_names.length - 1; i >= 0; i--) { // I modified this line.
  console.log(Concat_names[i]);
  var check_included_units = Concat_names[i].includes("Included Units");
  console.log(check_included_units)
  if (check_included_units == true) {
    Concat_names.splice(i, 1);
  } else if (check_included_units == false) {
    continue;
  }
}
console.log(Concat_names); // [ 'Test 1-Coms-2A Up', 'test 2-Percentage-MB' ]

  • As another approache, I think that you can also use the following script.

var Concat_names = ["Test 1-Coms-2A Up", "Test 1-Included Units-10G", "test 2-Included Units-1000 Sa", "test 2-Percentage-MB"];
var res = Concat_names.filter(e => !e.includes("Included Units"));
console.log(res)

  • Related