Utilizing App Script for Filtering Data with Multiple Criteria

Having trouble transferring data from a data sheet to my report sheet using multiple criteria for matching. I wrote some code that worked, but it's returning all data instead of filtering by criteria.

I want the function to search for column criteria and skip it if it's empty. For example, if Col B has 'name' as a criteria and Col F has 'case', I only want to see rows that match both criteria. If I add another criteria in Col C like 'agency' and filter again, I want to see results based on all 3 criteria.

This is the current code:

function myReport(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var datasht = ss.getSheetByName("CURENT POOL DATA SHEET");
var reportsht = ss.getSheetByName("REPORTS")
var rng = datasht.getRange(2, 1, datasht.getLastRow(),14).getValues();
var Criteria1 = reportsht.getRange("B4").getValue();
var Criteria2 = reportsht.getRange("C4").getValue();
// Remaining Criteria variables omitted for brevity

var fData = rng.filter(function(e){return e[1]==Criteria1 || e[2]==Criteria2 
|| e[3]==Criteria3 || e[4]==Criteria4 || e[5]==Criteria5 || e[6]==Criteria6 || e[7]==Criteria7 
|| e[8]==Criteria8 || e[9]==Criteria9 || e[10]==Criteria10 || e[11]==Criteria11 
|| e[12]==Criteria12 || e[13]==Criteria13 });

reportsht.getRange(5,1,fData.length,14).setValues(fData);
}

function clearFilter() {
  var myGoogleSheet= SpreadsheetApp.getActiveSpreadsheet(); 
  var shUserForm    = myGoogleSheet.getSheetByName("Reports"); 
  var ui = SpreadsheetApp.getUi();
  var response = ui.alert("Reset Confirmation", 'Do you want to reset this form?',ui.ButtonSet.YES_NO);

 if (response == ui.Button.YES) {
  shUserForm.getRange("A5:N3724").clear(); 
  shUserForm.getRange("A5:N3724").setBackground('#FFFFFF');
  
  return true;
 }
}

Adding image of the report sheet below

Still learning Apps Script, trying to get the hang of it.

Answer №1

Your approach seems to be a little off track. There is a more efficient way to execute this type of query using the formula =QUERY(). You can find more information on how to do it here. If you prefer using a script, I recommend making some improvements to your code.

Avoid repeating queries like this:

var criterias = reportsht.getRange("B4:N4").getValues();
// criterias[0][1] == Criteria1 ....

Instead of checking for any data in the "criteria", consider validating if the data matches the criterion. Using the filter() function would be a better option to narrow down the array based on your conditions. criterias.filter()

var fData = rng.filter(function(e){return e[1]==Criteria1 || e[2]==Criteria2 
|| e[3]==Criteria3 || e[4]==Criteria4 || e[5]==Criteria5 || e[6]==Criteria6 || e[7]==Criteria7 
|| e[8]==Criteria8 || e[9]==Criteria9 || e[10]==Criteria10 || e[11]==Criteria11 
|| e[12]==Criteria12 || e[13]==Criteria13 });
//var fData = rng.filter(function(e){return e[1]==criteria1});
reportsht.getRange(5,1,fData.length,14).setValues(fData);
}

For more details, check out this link. Hope this aids in enhancing your methodology!

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

Avoiding code duplication in Angular: tips for optimizing functions

Is there a way to avoid repeating the same for loop for a second variable and use only one? I'm trying to apply the "Don't repeat yourself" method here. Should I consider using an array? JS: var app=angular.module('xpCalc', []); app.c ...

Is there a way to serve an HTML file using the response object in expressjs while also incorporating an external JavaScript file?

My express application successfully serves an HTML page from my disk when I initially make a GET request to "http://localhost:3000/" in the browser. Now, I am trying to access a JavaScript file that is located in the same directory on the disk as the HTML ...

Sending data from configuration to factory in AngularJS and UI Router

Trying to perform a search in an http call with a dynamic value based on the current view. The factory setup is as follows: .factory('SearchService', ['$http','$filter', function($http, $filter) { var service = { get ...

Is there a way for me to retrieve the locator value of a webelement?

How can I retrieve the selector value used in a selenium webelement in javascript? Let's say I have the following object: var el = browser.driver.findElement(by.id('testEl')); I want to extract the text 'testEl' from this object ...

Deactivating Cluetip tool tips and adjusting the height limit in JQuery

How can I momentarily turn off the hints? I have seen references to being able to do so on the website and in this forum, but I am having trouble locating the command to disable them. I just need to temporarily deactivate them and then enable them again. ...

Passing state to getStaticProps in Next JSLearn how to effectively pass state

I am currently fetching games from IGDB database using getStaticProps and it's all working perfectly. However, I now have a new requirement to implement game searching functionality using a text input field and a button. The challenge I'm facing ...

transferring documents using multer

As a novice in JavaScript, I am exploring the use of multer for file uploads. Below is my current code: let express = require('express'); let im = require('imagemagick'); let gm = require("gm").subClass({ imageMagick: true }); let ...

CRUD operations are essential in web development, but I am encountering difficulty when trying to insert data using Express

I am currently attempting to add a new category into the database by following the guidelines provided in a course I'm taking. However, I am encountering difficulties as the create method does not seem to work as expected. When I try it out in Postman ...

The JavaScript class failed to work properly within the asp.net framework

I have successfully implemented a JavaScript function on my aspx page. Here is the code snippet: <script type="text/javascript"> $(document).ready(function () { console.log("ready!"); var options = []; var ...

Unable to retrieve JSON element in ReactJS

Here is the code snippet that I am currently working with: const [questions, setQuestions] = useState([]) useEffect(() => { let idVar = localStorage.getItem('idVarianta'); idVar = JSON.parse(idVar) axios({ ...

Utilizing the power of async/await to simplify Hapi17 route abstraction

Trying to understand the transition to async/await in Hapi 17 is a bit of a challenge for me. My main focus is figuring out how to modify an abstracted route to make it compatible with async/await. Here is a snippet from my routes\dogs.js file: con ...

Unable to access the contents of an array (React JS)

After fetching the content as an array and viewing its contents with console.log, I noticed that despite the array being populated, it has a length of 0, making it impossible to retrieve its elements using map. What could be causing this issue? https://i. ...

Using JavaScript, concatenate text from each line using a specified delimiter, then add this new text to an unordered list element

I am looking to extract text from named spans in an unordered list, combine them with a '|' separating each word within the same line, and append them to another ul. Although my code successfully joins all the words together, I'm struggling ...

Waiting for state changes in React by using the UseState Hook

I am currently working on a function that manages video playback when clicked, and I need to set consecutive states using the useState hook. However, I want to ensure that the first state is completed before moving on to the next setState without relying ...

What is the most effective method for transmitting a zip file as a response in Azure functions with node.js?

With the Azure function app, my goal is to download images from various URLs and store them in a specific folder. I then need to zip these images and send the zip file back as a response. I have successfully achieved this by following these steps: Send ...

Implementing gridlines on a webpage using HTML and JavaScript to mimic the grid layout found in Visual Studios

Currently, I have a grid snap function in place, however, I am looking to add light grey lines horizontally and vertically on my Designing application. The goal is to achieve a similar aesthetic to Visual Studios' form designing feature. Utilizing so ...

Positioning oversized images in a React Native application

Looking to showcase two images side by side using React Native, where I can customize the screen percentage each image takes up. The combined size of the images will exceed the horizontal screen space available, so I want them to maintain their original di ...

Utilize the function of express

The following code is not behaving as expected: var express = require('express'); var app = express(); app.use(function(req, res, next) { console.log('first statement'); next(); }, function (req, res, next) { console.log('se ...

consolidating express routes in one consolidated file

I am attempting to consolidate routes into a single file using app.use app.js import express from 'express' import testRouter from 'testRouter' const app = express() app.use('/testRouter', testRouter) app.listen(3000) tes ...

Adjusting the background opacity when the sidebar is open in a React + Typescript project

I am currently working on customizing a sidebar using the react-pro-sidebar library along with React and Typescript. The sidebar layout seems to be in order, but I am facing difficulty in adjusting the background color of the rest of the screen when the si ...