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

Using Vue.js to pass a variable from a parent component to a child component

Parent component: ShowComment Child component: EditComment I'm attempting to pass the value stored in this.CommentRecID to the child component. In the template of ShowComment, I have included: <EditComment CommentRecID="this.CommentRecID" v-if= ...

Using arrays as props in React with Typescript

In my code, I have a Navbar component that contains a NavDropdown component. I want to pass an array as a prop to the NavDropdown component in order to display its dropdown items. The array will be structured like this: DropDownItems: [ { ...

Command in Selenium Webdriver for initiating a mouse click

Currently, I am in the process of writing tests for a Java application that has been created with the Vaadin framework. To conduct these tests, I have opted to utilize the Robot Framework. In certain instances, I must implement robot framework commands suc ...

Every time I try to utilize "useCallback," it results in a TypeError error popping up

I am struggling with an issue related to a const experience that involves creating 6 experiences with their respective popovers. I have been instructed to use useCallback, but every time I attempt to do so, I encounter an error message. This relates to my ...

What is the correct RegEx pattern I should use to properly match the provided test case without including the ending period?

Regular Expression: /@([\S]*?(?=\s)(?!\. ))/g Given String: 'this string has @var.thing.me two strings to be @var. replaced'.replace(/@([\S]*?(?=\s)(?!\. ))/g,function(){return '7';}) Expected Result: ...

ExtJS variable not populating with servlet data

I'm facing an issue with my code where I am calling a servlet from JavaScript using an AJAX request. The data from the servlet is shown in a message box within the success function, but it's not being loaded into a variable called `myData` in Jav ...

Getting data from a document containing key value pairs

I have a collection of text files that are structured in a key-value pair format. "Site Code": "LEYB" "Also known as": "" "Location": "Pier Site, Poblacion del Sur, Villaba, Southern Leyte" "Contact person(s)": "" "Coordinates[1]": "11 ...

Are we retrieving multiple APIs the right way?

Looking for some guidance on fetching two APIs in React. I have created two functions to handle this task and called them simultaneously within another function. Should I stick with this approach or move the API calls to componentDidMount? Additionally, I& ...

Having trouble passing a token for authentication in Socket.IO v1.0.x?

I am currently following a tutorial on creating a token-based authentication system, which can be found here. I have implemented the following code: Code in app.html: var socket = io('', { query: "token=i271az2Z0PMjhd6w0rX019g0iS7c2q4R" }); ...

Secure your Express.js session cookies for enhanced protection

Struggling to figure out how to set a secure cookie in the expressjs framework. Any suggestions on where I can find an option for this? ...

Implementing a Searchable Autocomplete Feature within a Popover Component

Having an issue saving the search query state. https://i.stack.imgur.com/HPfhD.png https://i.stack.imgur.com/HbdYo.png The problem arises when the popover is focused, the searchString starts with undefined (shown as the second undefined value in the ima ...

Tips for preventing Chrome from masking the background image and color on an autofill input

Google Chrome Browser has caused the background-color and background-image effects to be removed from the Username and Password input fields. Before autocomplete https://i.stack.imgur.com/Ww7Hg.png After autocomplete https://i.stack.imgur.com/hbG2C.png ...

Identifying and detecting Label IDs when clicked using the for tag

I am facing an issue with labels and input fields in my code. I have multiple labels that trigger the same input field, but I want to know which specific label triggered the input field. <label id="label1" for="input1">Document1</label> <la ...

Eliminate the jQuery AJAX timestamp from the URL parameters

Is there a way to eliminate the jQuery AJAX cache buster code (_=3452345235) from string URLs? While working on a global AJAX fail handler, I need to identify which URL failed. However, every time I locate the failed request's URL, the jQuery cache q ...

When attempting to push `content[i]` into an array in AngularJS, it is flagged

In my JSON data, I have the following structure: var data = [{ id: 1, name: 'mobile', parentid: 0, limit:3 }, { id: 2, name: 'samsung', parentid: 1 }, { id: 3, name: 'moto', parenti ...

Ways to create dynamic functionality with JavaScript

I need to iterate through the document.getElementById("b") checked in a loop. Is this achievable? How can I implement it? <img class="img-responsive pic" id="picture" src="images/step1.png"> <?php //get rows query ...

Problem arising from apostrophe usage in Javascript OData request

In my current project, I have a text input field that passes a value through JS to fetch filtered data of names from a JSON file using OData query parameters. However, I've encountered an issue where if a name contains an apostrophe, it results in a ...

Adding HTML content inside an iFrame at a specific cursor position in Internet Explorer

Does anyone know a method to insert HTML into an iFrame specifically for IE? I have been using execCommand insertHtml in Chrome and Firefox, but it doesn't seem to work in IE. I was able to paste HTML into a content editable div using pasteHTML, howe ...

What are some ways to prevent manual page reloading in Node.js when using EJS?

Currently, I am utilizing Node as a server and frontend in EJS. My project involves working with socket.io, which is why it is essential that the page does not refresh manually. If a user attempts to reload the current page, the socket connection will be d ...

Improving the display of events with fullcalendar using ajax requests

I have integrated the fullcalendar plugin from GitHub into my project. I am looking to implement a feature where I can retrieve more events from multiple server-side URLs through Ajax requests. Currently, the initial event retrieval is functioning proper ...