Error: Attempting to access the 'length' property of an undefined variable in a Google Sheets document

Could someone help me troubleshoot this issue I'm encountering in Google Sheets Apps Script: "TypeError: Cannot read properties of undefined (reading 'length')"? I found this script on YouTube and tried to implement it.

Below is the code snippet:

function showInputBox(){

 var ui = SpreadsheetApp.getUi();
 var input = ui.prompt("Please enter your Name.", ui.ButtonSet.OK_CANCEL);

if(input.getSelectedButton() == ui.Button.OK){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var ws = ss.getSheetByName("original");
  var data = ws.getRange("A2:G" + ws.getLastRow()).getValues();
  var userSelectedRep = input.getResponseText().toLowerCase();
  var newData = data.filter(function(r){ return r[2] == userSelectedRep });
  var newWs = ss.insertSheet(userSelectedRep);
  newWs.getRange(2, 1, newData.length, newData[0].length).setValues(newData);
}

Answer №1

If you encounter the error message,

TypeError: Cannot read properties of undefined (reading 'length')
, it could be due to unsafe data access as newData may be empty if no rows meet the filter criteria.

To address this issue, I have added a check for newData below.

Additionally, make sure to use toLowerCase() instead of tolowercase.

function showInputBox() {
  var ui = SpreadsheetApp.getUi();
  var input = ui.prompt("Please enter your Name.", ui.ButtonSet.OK_CANCEL);

  // Verify if OK button was clicked
  if (input.getSelectedButton() == ui.Button.OK) {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var ws = ss.getSheetByName("original");
    var data = ws.getRange("A2:G" + ws.getLastRow()).getValues();
    
    // Convert user input to lowercase
    var userSelectedRep = input.getResponseText().toLowerCase();

    // Filter data based on user input
    var newData = data.filter(function(r) {
      return r[2].toLowerCase() == userSelectedRep;  // Make sure comparison is case-insensitive
    });

    // Check if any matching data was found
    if (newData.length > 0) {
      // Create a new sheet and insert the filtered data
      var newWs = ss.insertSheet(userSelectedRep);
      newWs.getRange(2, 1, newData.length, newData[0].length).setValues(newData);
    } else {
      ui.alert("No matching data found for the entered name.");
    }
  } else {
    ui.alert("Operation canceled.");
  }
}

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

How can one retrieve the set-cookie value in a <meta http-equiv> tag using Node.js?

When working with Node.js, I am encountering a scenario where I need to detect instances of a cookie being set in a response so that I can make changes to it. There are two ways in which cookies are being set: Through the use of the set-cookie HTTP heade ...

Is there a tool that can help pinpoint the original collection for shared elements across multiple collections?

When given multiple collections/arrays, I am interested in identifying the common elements and which collections they belong to. This request is somewhat similar to this query, but there may be matching elements between collection1 and collection3, or eve ...

Learn how to effortlessly update models by integrating AngularJS with Django and Django Rest Framework

Here is a JSON representation of a post based on its ID: http://127.0.0.1:8000/update/1?format=json {"title": "about me", "content": "I like program", "created": "2014-11-29T18:07:18.173Z", "rating": 1, "id": 1} I am attempting to update the rating ...

Unlock the full potential of your database with ExpressJs and MySQL. Discover a superior option to Knex Interceptor for securing your data with

I have a dilemma with managing sensitive data in my MySQL tables. I need to encrypt these fields before insertion and decrypt them when retrieving the data. Here are three different approaches that I have considered: One option is to implement a DATABAS ...

Creating Particle Systems using THREE.js

In my current game development project, I am aiming to incorporate visually striking effects like smoke, flame, and blast. Utilizing the THREE.js library for this purpose has proven to be quite challenging. Despite experimenting with various techniques, ...

Creating a responsive HTML5 webpage that adjusts seamlessly to all screen sizes without the need for scrolling

I have developed an HTML5 application for mobile devices. Currently, I have managed to address width-height issues by using a simple scroll feature when necessary. However, I have encountered a challenge with a particular page that contains a lot of conten ...

The clear icon in React will only appear when there is a value inputted

Is there a way to implement the clear X icon that only appears when typing in the input field using reactjs, similar to the search input on the Google homepage? Check it out here: https://www.google.com import { XIcon } from '@heroicons/react/solid&ap ...

What is the process of transforming a string into a JSON object?

var str = '""{""as"":""N9K-93180YC-EX""}""'; I attempted to remove the extra quotes using a regular expression: var str1 = str.replace(/\"/g, ""); After removing the extra quotes, the string now looks like "{as:N9K-93180YC-EX}". However, ...

Vue.js displays an error: TypeError - "this is undefined" when executing JavaScript

Looking to create a dynamic water pipe with flowing water. Unfortunately, the front picture displays an error message. https://i.sstatic.net/FyNSK.png https://i.sstatic.net/BZu47.png The next image represents a method within the Vue page. Uncertain if i ...

What is the reasoning behind placing CDN links at the bottom of the index file?

What is the reason for placing CDN links for AngularJS file at the end of the index page? I initially placed it at the top of the file and it worked fine. Is there a significant difference between these two placements? ...

Convert an array comprising arrays/objects into JSON format

This problem is really challenging for me. The structure of my array goes like this: array1 = [ [array2], [array3], [array4] ... [array17] ] array2 = [ ['obj1'], ['obj2'], ['obj3'] ... ['obj30'] ] ... ... obj1 = ({p ...

Issue with nivo-lightbox not opening upon clicking image

I have diligently followed the instructions to set up this JavaScript plugin, but unfortunately it doesn't seem to be functioning properly. The plugin I'm using can be found here: All the links to the CSS, theme, and JavaScript files are display ...

JS limits browsers to downloading only 10 images simultaneously

Is there a way to increase the number of simultaneous downloads beyond the current limit of 10 in the code below? transferFiles(){ this.checkMark = true let i = 0 this.finalImages.forEach((image) =>{ i++ saveAs(image, 'imag ...

Ways to induce scrolling in an overflow-y container

Is there a way to create an offset scroll within a div that contains a list generated by ngFor? I attempted the following on the div with overflow-y: @ViewChild('list') listRef: ElementRef; Then, upon clicking, I tried implementing this with s ...

What are some methods to maintain active MySQL connections in a Node.js environment?

In my Node.js application, I have noticed that mysql connection pools expire after a period of idle time, resulting in delays when performing queries as new connections need to be created. This delay is unacceptable and I am seeking a solution. My idea is ...

Retrieve specific information by clicking a button within a table cell on the data grid in React.js

I am just starting out with React and have a query. I have set up a data table with some dummy information using a React data table. How can I make the cells of the table clickable so that when clicked, the data is displayed on a form located on the same p ...

What advantages does using a callback offer compared to await?

For a project focused on user-related tasks, I crafted the following code snippet within my service file. let result: User | null = await userModel.registerUser(); return result; After receiving feedback from my team advising to "Use callback rather than ...

Exploring AngularJS's capabilities with Cross Domain POST requests

One query I have concerning CORS requests that include the HTTP Authorization header: I've noticed that the web browser doesn't seem to send the Authorization header with POST requests, is there a workaround for this? Below is the Angular code ...

What is the proper way to utilize a variable as a field name in a Mongo query within the Meteor framework?

Is there a way to utilize a variable as a field name in a Mongo query within a Meteor application? For instance... This code snippet performs a find operation on my request controllers collection after capitalizing the collection name for the parent id o ...

Is there a way to set up gulp without relying on npm when using shared hosting?

While working on my shared hosting, I encountered a roadblock regarding the installation of gulp for compiling LESS assets into CSS. The hosting administrator has declined to install npm, which is essential for setting up gulp. Given this limitation, I am ...