Unleashing the Power of Google Apps Script Filters

Having some data in a Google Sheet, I am looking to filter it based on specific criteria and return corresponding values from another column. Additionally, I need to count the number of elements in the resulting column. Below is an example of the data:

Sample data

A B
1 Initials Application Reference
2 MWB.KBB 1001
3 JET,JJB 1002
4 KBB 100,310,041,005
5 MKGC 1006
6 KBB 1007

If we want to filter the data by searching for "KBB," we should retrieve all cells containing that word, which should be three (3) cells. However, currently only two cells are being returned. The first row with two elements in a single cell is not being included, but it should be. Lastly, we need to count the elements in the returned column following the criteria.

Here is the code attempted:

function filter(){
  //opened ss via url
  const ws = ss.getSheetByName("Sample");
  const range = ws.getRange(2,1,ws.getLastRow() - 1,2).getValues();

  const initial = range.map(function(n){return n[0];});
  const filtered = initial.filter(filterLogic);

  Logger.log(initial); // [MWP, KBB, JET, JJB, KBB, MKGC, KBB]
  Logger.log(filtered); // [KBB, KBB]
}

function filterLogic(name){
  if(name == "KBB"){
    return true;
  } else {
    return false;
  }
}

The above code addresses the set criteria but does not include the counting of elements for the returning value from another column post-filter application.

How can we modify this process to incorporate the first row containing the text "KBB" in the filtered data? Are there alternative methods to achieve this?

Answer №1

Programming Script:

function searchForKBB(n = "KBB") {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Sheet0");
  const osh = ss.getSheetByName("Sheet1");
  let results = sh.getRange(1,1,sh.getLastRow(),sh.getLastColumn()).createTextFinder(n).matchEntireCell(false).findAll().map(rg => [rg.getA1Notation()]);
  results.unshift(["Ranges"]);
  osh.getRange(1,1,results.length,results[0].length).setValues(results)
}

Data Information:

First Column Second Column
1 Initials Application Reference
2 MWB.KBB 1001
3 JET,JJB 1002
4 KBB 100,310,041,005
5 MKGC 1006
6 KBB 1007

Outcome of Search:

Ranges
A2
A4
A6

Answer №2

Here is a solution you can try out:


function getAllKBBs(){
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var ss1 = ss.getSheetByName("YOUR_SHEET_NAME");
      var range = ss1.getRange(1,1,ss1.getLastRow(),4).getValues();
      output = whenTextContains("KBB", range, 1, 1);
      Logger.log(output.length);
} 

You can find the whenTextContains() function in this repository: https://github.com/NikolaPlusEqual/GoogleAppsScriptFilters/blob/main/Functions

Alternatively, you can copy and paste the following code into your script and call the above function:


function letterToColumn(letter){
  var column = 0, length = letter.length;
  for (var i = 0; i < length; i++)
  {
    column += (letter.charCodeAt(i) - 64) * Math.pow(26, length - i - 1);
  }
  return column;
}

var setData = {}

function whenTextContains(txt, rng, col, targetCol = 0){
  if (typeof col == "number" && typeof txt == "string"){
    setData.col = col;
    setData.txt = txt;
  }
  else{
    return;
  }
  var output = rng.filter(wtc);
  if(targetCol == 0){
    return output;
  }
  else if(typeof targetCol == "number"){
    var result = output.map(function (item) {
      return item[targetCol-1];
    });
    return result;
  }
  else if(typeof targetCol == "string"){
    var targetnum = letterToColumn(targetCol);
    var result = output.map(function (item) {
      return item[targetnum-1];
    });
    return result;
  }
  else{
    return;
  }
}

function wtc(ar){
  var txt = setData.txt;
  var col = setData.col - 1;
  var str =  ar[col].toString();
  return str.includes(txt);
} 

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

React - callbackFromApp function is executing only one time when clicked

Whenever I click a button within my child React module, it is meant to increment the timer and then pass back the timer in minutes and total seconds to the parent component where it will be stored as state. The issue I am facing is that when I click the b ...

"Encountering an issue with Next.js where the Redux

Hey there, I'm working on a simple project using Nextjs. I need to access the state of my Redux store but I'm encountering an error when trying to use store.getState, it's throwing an error saying getState is undefined. Additionally, I have ...

Trouble with the Ngx-Captcha feature

I am currently utilizing https://www.npmjs.com/package/ngx-captcha/v/11.0.0. <ngx-recaptcha2 #captchaElem [siteKey]="'6Leh1ZIjAAAAAG8g0BuncTRT-VMjh3Y7HblZ9XSZ'" (success)="handleSuccess($event)" [useGlobalDomain]="fals ...

Mongoose and MongoDB in Node.js fail to deliver results for Geospatial Box query

I am struggling to execute a Geo Box query using Mongoose and not getting any results. Here is a simplified test case I have put together: var mongoose = require('mongoose'); // Schema definition var locationSchema = mongoose.Schema({ useri ...

Steps for creating an HTML report using Intern JS

Our team relies on intern JS for automating functional tests, however we are facing difficulty in generating an html report. I attempted to use locvhtml as suggested by the Intern documentation (https://theintern.github.io/intern/#reporter-lcov), but unfo ...

The onprogress event for the XMLHttpRequest object threw an error due to an Uncaught SyntaxError, indicating

I have implemented an ajax function successfully However, I am facing an issue where when using onprogress, I sometimes receive incomplete HTML response and the console displays Uncaught SyntaxError: Invalid or unexpected token but the function still cont ...

Steps to releasing JavaScript and asset files on npm

I have created a custom UI component for internal company use and released it on npm. However, after installing the package, I noticed that only the index.js file is showing up in the node_modules directory. I am not utilizing any package builders or ES m ...

Accessing PHP variables within a React componentTo access external

How can I pass the id selected in a menu from a react component to a PHP file, after already knowing how to send data from PHP to the react component? $.ajax({url: '/file.php', type: 'POST', dataType: 'json', ...

Creating a personalized script in ReactJS: A step-by-step guide

If I have already built a component with Google Chart in ReactJS, and I want to implement a feature that allows the Legend to show/hide data using a JavaScript script provided here, how and where should I integrate this code to work with my chart? Here is ...

A JavaScript String Utilizing an HTML Document

When developing applications for my website using JQuery, I encountered an issue with pulling an html document into a string. I want the application button to open a window with the html document inside. I am attempting to modify this string variable with ...

How to Retrieve the Value of <input type=date> Using TypeScript

I am currently developing a survey website and need assistance with retrieving user input for two specific dates: the start date and end date. I aim to make the survey accessible only between these dates, disabling the "take survey" button after the end da ...

Fetching chat messages using an AJAX script depending on the timestamp they were sent

I am currently working on developing a real-time chat application with various rooms as part of my project. Progress has been smooth so far, but I am facing an issue with properly fetching the most recent chat messages from the database. The message table ...

"Executing the ajax send() function does not result in any changes to the

Just starting to explore ajax and I need some help. Can anyone explain why the address bar is not updating when using ajax send()? The connection is working, but it keeps displaying "There is no variable!" PS: Please note that I prefer not to use JQuery. ...

Facing difficulties in resetting the time for a countdown in React

I've implemented the react-countdown library to create a timer, but I'm facing an issue with resetting the timer once it reaches zero. The timer should restart again and continue running. Take a look at my code: export default function App() { ...

Selenium: The function moveToElement is not valid for the driver.actions() method

After creating all my tests using Selenium IDE, I decided to export them to JavaScript Mocha for running in travis. While the tests run smoothly in Selenium IDE and can be exported, I encountered an issue when trying to run them which resulted in the erro ...

Real-time Property Availability Widget

I need assistance with creating a website for a homeowner who wants to rent out their property. The client requires a feature that allows them to log in and easily mark individual days as available or unavailable for rental by choosing specific colors for ...

Error callback not being invoked on save() method in AngularJS service

So I am currently using the AngularJS Restful Service $resource in my project. However, when I try to call the $save function and provide an error callback, it does not get invoked. Surprisingly, even though the server sends a 418 error, which is not a suc ...

The alignment of Bootstrap table headers in a Vue.js component needs adjusting for better display

Is there a way to ensure proper alignment of headers and column bodies in my Vue.js DataGrid component when utilizing the vuedraggable package for column reordering? Below is the code snippet for my DataGrid.vue component: <template> <div class ...

What could be causing my Bootstrap 5 hover effect to malfunction?

Can anyone help with changing the hover effect of a bootstrap button in my code? Here's the HTML: <button type="button" class=" btn btn-dark">Sign Up</button> And here's the CSS I tried: .btn-dark:hover { color: ...

transmitting information using dataURL

Hey there! So I've got this code that does a neat little trick - it sends a dataURL to PHP and saves it on the server. In my JS: function addFormText(){ $('body').append('<input type="hidden" name="img_val" id="img_val" value="" /& ...