Remove specific data regardless of letter case from the row

I've developed a Google Apps Script that scans specific columns for certain keywords and deletes rows that contain them:

function filterRows() { 
  var sheet = SpreadsheetApp.getActiveSheet(); 
  var rows = sheet.getDataRange(); 
  var values = rows.getValues(); 
  var rowsDeleted = 0; 
  var searchWords = ['furniture takeover','can be taken over','caravan','trailer'] 

  for (var i = values.length - 1; i >= 0; i--) {  
    var row = values[i]; 
    for (var j = 0; j < searchWords.length; j++) {    
      if (row['21','17'].indexOf(searchWords[j]) > -1) {         
        sheet.deleteRow(i+1);     
        rowsDeleted++;   
        break;         
      }
    } 
  } 
};

Is there a way to make the keyword check not case-sensitive? For example, if I include "apartment rental", it should remove all matches of: APARTMENT RENTAL, apartment rental, Apartment Rental?

Answer №1

Explanation:

  • To achieve the conversion of every element in the row array to lowercase, utilize the map() function along with toLowerCase(). This approach ensures that toLowerCase is applied to each element within the row array. Implement this modification as shown below:

    if (row.map(r=>r.toLowerCase()).indexOf(arrayOfWords[j]) > -1)
    
  • The syntax row['21','17'] does not conform to valid JavaScript object standards since you cannot slice an array in this manner. If your intention is to specifically target columns 21 and 17, then adjust the if statement as follows:

    if ([row[21],row[17]].map(r=>r.toLowerCase()).indexOf(arrayOfWords[j]) > -1)
    

    Additionally, take note that row[21] corresponds to column V and row[17] corresponds to column

    R</code within the sheet. Remember that JavaScript indexing starts at <code>0
    , where 0 represents column A, 1 represents column B, and so on.


Solution:

function sort() { 
  var sheet = SpreadsheetApp.getActiveSheet(); 
  var rows = sheet.getDataRange(); 
  var values = rows.getValues(); 
  var rowsDeleted = 0; 
  var arrayOfWords = ['möbelübernahme','können übernommen werden','caravan','wohnwagen'] 

  for (var i = values.length - 1; i >= 0; i--) {  
    var row = values[i]; 
    for (var j = 0; j < arrayOfWords.length; j++) {    
      if (row.map(r=>r.toLowerCase()).indexOf(arrayOfWords[j]) > -1) {         
        sheet.deleteRow(i+1);     
        rowsDeleted++;   
        break;         
      }
    } 
  } 
};

Answer №2

A different approach to solve the issue

One way to tackle this is by utilizing the toLowerCase() method - for instance, transforming "Mietwohnung" into "mietwohnung", which allows for a seamless comparison.

To implement this change in your script, you can modify it as follows:

for (let i = values.length - 1; i >= 0; i--) {
   var row = values[i];
   var found = false;
   for (let k = 0; k < row.length; k++)
      for (let j = 0; j < arrayOfWords.length; j++)
         if (row[k].toString().toLowerCase().indexOf(arrayOfWords[j]) > -1)
            found = true;
   if (found == true) {
      sheet.deleteRow(i + 1);
      rowsDeleted++;
   }
}

The provided script iterates over all data values within the range and employs the additional loop to check each value against the words in the arrayOfWords array after converting them to lowercase using toLowerCase(). If a match is found, the corresponding row(s) are removed. The variable found acts as a marker for detecting whether the word was located or not.

Resource

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The JavaScript indexOf method in an unordered list incorrectly returns the index of a specific event

Looking to retrieve the index number of an 'li' element within a 'ul' from the HTML structure. I attempted to convert the 'ul' into a list and access its children using: [...ul.children] However, upon targeting any of the chi ...

The browser freezes after a short delay following an Ajax request

I recently created an admin panel with notification alerts using Ajax. Initially, everything was working smoothly, but after a few minutes, the browser started freezing. I'm new to Ajax development, so I'm unsure what could be causing this issue. ...

A guide on leveraging the each() method for looping through a JSON document

I am hoping to display elements sourced from a JSON file. Here is the JSON data "2015": { "img": "<img src = \"../images/images/images_of_members/image1.jpg\">", "img2": "<img src = \"../images/images/images_of_members/image2.jpg& ...

Updating ng-model with the values from a property in a collection in AngularJS

Encountering an unusual problem with setting the ng-model for a select drop-down menu. Despite using a property value that matches one in the ng-options, the ng-model consistently ends up as null. Below is the function responsible for fetching orders: o ...

Load the values into the dropdown list based on the selection from the previous dropdown menu

Currently, I am working on implementing cloning functionality for select boxes. There are 3 select boxes: country, state, city. The user selects the country first which then populates the state select box based on the ID, and similarly, the city dropdown ...

No tests were found to run when Karma was executed using the ng test command

I'm facing an issue with my Angular 10 project where Karma is not detecting my default and custom spec.ts files for execution. Any ideas on why this could be happening? Here is a snapshot of my unchanged Karma Config file: // Karma configuration file ...

How should filtering be properly done on a data array within a Redux reducer function?

I am trying to develop a function that filters an array based on a search input. The goal is for the filter action to trigger when there's a change in the SEARCH_TEXT. However, I'm facing confusion when it comes to handling the state when the del ...

Python 3 Selenium struggles to run JavaScript code

I'm currently working with Python 3 and utilizing Selenium to extract data from a website. I am attempting to eliminate a specific class from a list item in order to successfully display the desired information. Here is the code snippet in question: ...

While attempting to import modules in Visual Studio Code, an error message appears stating "Unexpected token {"

Greetings! I am currently using Visual Code to run my project and would like to share my code with you. In the file external.js: export let keyValue=1000; In the file script.js: import {keyValue} from './external.js'; console.log(keyValue); ...

Retrieving a Promise's value for an HTML Element

Hello, I'm new to working with React and JavaScript and could use some assistance. I have a function that returns a Promise that includes an interface. My goal is to access a variable in the interface and use it within <dl><dt>{//string va ...

Designing a button component with text

Exploring My Demo Page, I am attempting to design a button that will serve as a closure mechanism for modals. The code snippet I experimented with is as follows: x=document.createElement('button'); x.className='superclose'; Referencin ...

The code is functioning properly and executing without issues, yet I am puzzled as to why an error message is appearing in the console stating "Uncaught TypeError: Cannot read properties of null (reading 'style')"

Hey there, I'm new to the world of JavaScript and trying my hand at creating multiple modals that pop up. Everything seems to be working fine when opening and closing each modal, but I keep encountering an error message in the console (Uncaught TypeEr ...

Update $(img).offset() upon clicking and dragging the image

Whenever I click on an image, it moves to a random position. I want different sounds to play based on where the click occurs: Directly on the image Within 50px of the image More than 50px away from the image. To achieve this, I need to constantly updat ...

Issue with Axios in my React Application: Unidentified SyntaxError

As I attempt to connect to my database using axios, a frustrating error appears in my vsCode terminal. The error message reads as follows: SyntaxError: C:\Users\Kelly Owoju\Desktop\Kelly Bright\my-web-app\node_modules\a ...

Getting the text value from a table in JavaScript is a straightforward process. By using

I am working with a table displaying available hotel rooms and want to change the text color to green if the room is marked as "available." Is there a way to check the innerHTML of a td element to see if it contains the word "available"? var status = do ...

What sorcery does Facebook use to alter the URL without triggering a page reload?

Similar Question: How can I update window location without a reload and # hack? Facebook and Ajax What method does Facebook use to change the URL without reloading the page? In the past, Facebook utilized the hash (#) symbol to prevent the page f ...

Creating an Array of Objects in JAVA - A Step by Step Guide

My task is to read a CSV file and store its data into an array of Objects, but I mistakenly created an ArrayList instead. Now, I need help figuring out how to fix this error as my attempts have been fruitless. Below is the code I used to read the CSV file ...

Passing data from parent AngularJS directive to child sub-directive

While working on my Angularjs project, I encountered an issue with directive nesting and passing variables. To start, I created a directive called 'header': .directive('header', [function() { return { restrict: 'E&apo ...

Deleting a precise key and value from a nested JSON array stored in a PostgreSQL column

I have a PostgreSQL table with a json object field named mytable.fields containing the following data { "a": "1", "b": [ { "c": 2, "d": 3 }, { "c": 4, " ...

Display a div using data from a Model in MVC

I am working with a model List that has fields ContainerId (div id) and Code (HTML code), which I am passing to a Razor View. Can you suggest the most effective way to display the code from the model in the containerId? My initial thought is to utilize j ...