降低匹配两个数组元素的复杂度

我写了一段代码,从Google表格中提取列标题(表格中的第一行),并将其与对象数组进行比较。对象数组中的每个对象都有3个属性:“问题”,“答案”和“类别”。该代码将每个列的标题与数组中每个对象的“问题”属性进行比较。

如果它们相似,则应将列的索引添加为某些字典的键,并将其值设置为包含答案和该问题类别的数组。无需过多解释我为什么要这样做,但是简要地讲,我建立了这种逻辑,以便能够为申请人对某些问题的答案评分(因此将问题的索引与其正确答案和类别联系起来)。这是代码:

 for (i = 0; i<columnHeaders[0].length; i++){
    for (j=0; j<questionsObjects.length; j++){
      //Get the current question and convert it to lower case
      question = questionsObjects[j].question.toString().toLowerCase(); 

      //Get column header, remove any spaces and new lines from it, and convert it to lower case
      columnHeader = columnHeaders[0][i].toString().toLowerCase();


      if (isStringSimilar(columnHeader, question)){

        //Link the column index to its corresponding question object
        var catAndAnswer = []; 
        catAndAnswer.push (questionsObjects[j].category.toLowerCase()); 
        catAndAnswer.push (questionsObjects[j].rightAnswer.toLowerCase()); 

        columnsQuestionsDictionary[i] = catAndAnswer; 
      } else {
        SpreadsheetApp.getActive().getSheetByName("log").appendRow(["no", columnHeader, question]); 
      }
    }
  }

代码运行良好,我唯一的问题是复杂性,它非常高。在某些情况下,该方法将花费近6分钟的时间执行(对于这种情况,我大约有40列和7个问题对象)!为了解开嵌套循环,我想到了将问题值(问题对象数组中所有对象的值)串联为1个单个字符串,在该字符串中,我在每个问题之前添加了对象数组中的索引。

例如:

  var str = ""; 

  for (j=0; j<questionsObjects.length; j++){

    str = str + j + questionsObjects[j].question.toString.toLowerCase();

  }

Then, I can have another separate loop through the columns headers, extract each header into a string, then use regex exec method to match that header in the long questions string (str), and if it's found I would get its index in str, then subtract 1 from it to know its index in the objects array. However, it turned out that the complexity of matching a regular expression is O(N) where N is the length of the string we search in (str in this example), given that this will be inside the columns loop, I see that we still get a high complexity that can go to O(N^2).

如何优化这些嵌套循环,以使代码以最有效的方式运行?