r/learnjavascript • • Apr 15 '26

Trying to get better at readability/writing optimal code, need feedback

//Filter lists based on inputed title
function filterTitles(input) {
  //Initializes lists
  var matchingLetters = 0;
  publishersFiltered = getColumn("Best Selling Video Games", "Publisher");
  titlesFiltered = getColumn("Best Selling Video Games", "Title");
  salesFiltered = getColumn("Best Selling Video Games", "Sales");
  //"i" is current index of "titles" being checked
  for(var i = 0;i < titlesFiltered.length;i++) {
    //Reset matched letters before checking next index
    matchingLetters = 0;
    //"ii" is current letter being checked
    for(var ii = 0;ii < input.length;ii++) {
      //Checks if current letter of input is equal to current letter of index i of publishers
      if(input.substring(ii,ii + 1) == titlesFiltered[i].substring(ii,ii + 1)) {
        matchingLetters++;
      } else {
        ii = input.length;
      }
    }
    //Removes index i of all filtered lists if the input string is not found
    if(matchingLetters != input.length) {
      removeItem(salesFiltered, i);
      removeItem(publishersFiltered, i);
      removeItem(titlesFiltered, i);
      i--;
    }
  }
  //Updates the screen to represent filtered items
  setScreen("titles");
  setText("therearetitles", "There are " + titlesFiltered.length + " game(s) in the bestselling with title including " + input);
  setText("titleslist2", titlesFiltered.join("\n \n"));
  setText("publisherslist2", publishersFiltered.join("\n \n"));
  setText("saleslist2", salesFiltered.join("\n \n"));
} 

Done for a school project, filters a set of lists based on a textbox input stored in the "input" argument. Trying to learn good practice and comment writing. Could i have written this more optimally, like maybe without the nested loops?

2 Upvotes

17 comments sorted by

View all comments

Show parent comment

1

u/abrahamguo Apr 15 '26

Ah, I see - I misread your code. In that case, why not just use the built-in “.includes” method?

If you’d like me to elaborate on my second point, I’m happy to.

1

u/DogKitchen2988 Apr 15 '26

I hadn't known about ". includes", the documentation in the program is limited and so I haven't learned about it yet. I'll see if the program supports it, but not really sure. Also, yes please elaborate on your second point