Combining each function in Google Sheets script with the && operator allows for setting a range of values to compare against the array

Looking for help with a coding issue involving checking data format before running specific code.

I've successfully implemented checks to prevent sending duplicate or empty data, but now I'm struggling with validating that the data is in the correct format of a four-digit number. Previously, I used conditional formatting to highlight any values outside the range of 1000 to 9999, and I'm trying to replicate this logic in my script to trigger an error message for incorrect formats.

The current section causing me trouble is the following else if statement:

else if (!data.every(function(num) {return num >= 1000 && num <= 9999})) {
    SpreadsheetApp.getUi().alert("You have incorrectly formatted tallies, tallies must be four digits.", SpreadsheetApp.getUi().ButtonSet.OK);
  }

Here is the complete code for reference:

 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var ssSheet = ss.getActiveSheet();

// Function to read and extract data
function readData() {
  // Code omitted for brevity
}

// Function to identify duplicates in data
function findDuplicates(dataAll) {
  // Code omitted for brevity
}

// Global variables declaration
var targetSheet = 'All Tallies';
var targetSpreadsheetID = 'id';
var targetURL = 'url';

// Main function to send data and timestamps
function sendDataAndTimestamp2() {
 // Code omitted for brevity
}

Answer №1

While reviewing the function sendDataAndTimestamp2(), it appears that removing empty values from the data variable is necessary. You can achieve this by using the filter(String) method:

var data = sourceRange.getValues().filter(String); // <-- here

. . .

else if (!data.every(function(num) {return num >= 1000 && num <= 9999}))

. . .

Alternatively, it's possible that you intended to use dataArray instead of data:

else if (!dataArray.every(function(num) {return num >= 1000 && num <= 9999}))

By the way, there is an opportunity to shorten the line slightly:

else if (!data.every(x => (x >= 1000) && (x <= 9999)))

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

JavaScript code for downloading data through AJAX and then loading a chart is not functioning as expected

<script> var highchartsOptions = { chart: { backgroundColor: 'rgba(255, 255, 255, 0.1)', type: 'column' }, title: { text: '' }, exporting: ...

Can you explain the functionality of the following Express router?

In the tutorial I am currently following, there are 2 router methods used to retrieve articles from the database. router.param('article', function(req, res, next, slug) { Article.findOne({ slug: slug}) .populate('author') .th ...

Tips for initializing a jstree with no content?

When I click a button, I send a key to the controller and retrieve my lists using JSON. The array inside my lists serves as my children in my jstree. $("#btnSearch").on("click", function () { alert("I'm also here"); $.ajax({ ...

How to dynamically delete React Router Link components after they have been clicked on?

When using React Router, how do I remove the div that contains a Link component or the Link component itself when it is clicked on and the routing is complete? For instance, consider an app structured in the following way: ==Header== ==Link1 Link2== Onc ...

The VueJS Watcher fails to activate when monitoring changes within nested objects

I have created a codesandbox to demonstrate my issue: codesandbox example watcher not triggering. Currently, I am developing a component that depends on an object with dynamically added data. In a separate .js file, I export the following object: export d ...

How to access JavaScript files from "bower_components" instead of "node_modules" using webpack

With the utilization of main-bower-files in my Gulp compilation tasks, it is not feasible for me to use webpack to require modules from the node_modules directory as it would interfere with the processing of CSS, images, and fonts in my current asset sys ...

Can we create a process that automatically transforms any integer field into a hashed string?

Is there a non-hacky way to hash all IDs before returning to the user? I have explored the documentation extensively but haven't found a solution that covers all scenarios. I am working with Postgres and Prisma ORM, managing multiple models with rela ...

What is the process for adding a line of JavaScript directly into the code (instead of using an external .js file)?

I am trying to insert a script tag that will run one line of JavaScript directly into the head of a document instead of inserting an empty script tag with a src attribute. So far, I have the following code: <script type="text/javascript"> var script ...

substituting the deep watcher in Angular

In my application, I am working with a data object called fulldata, which consists of an array of objects. fulldata = [ {'key': 'abc', values: {.....},....}, {'key': 'efg', values: ...

Exploring AngularJS for real-time updates from a persistent database

Hello, I'm new to Angular and currently working on an app that requires frequent polling of a URL every second. The retrieved data needs to be stored persistently for access across multiple views and controllers. To handle this, I've placed the ...

The function that iterates through the 'categoria' state and returns a new array is not functioning properly

Having difficulty with the object of a function using .map(). It works when the code is used directly, but not when put inside a function. For example: if(this.state.cat){ return _.map(this.state.cat, categoria => { if(this.state.search_ ...

"Is there a way to retrieve the upsertedId after performing an update using updateOne in MongoDB

I have freshly gathered information that I want to insert into my array of blog (My current collection structure is as follows):- { _id: 0, // other variables here..., blog: [ { _id: 0, title: 'Article 1&apo ...

How can we verify in enzyme that the history.push method was called while utilizing withRouter and connect?

In a stateless React component, I am utilizing withRouter and connect. Within this component, there is a button that triggers a method in props provided by mapDispatchToProps. My goal is to create a test that verifies the button's action of calling h ...

Modify the code to interpret a new JSON structure

I have a piece of code that is designed to read JSON data: $.getJSON("data.json", function(data){ var output = ''; $.each(data, function(index, value){ output += '<li>' + value.title + '</li>'; } ...

Updating HTML using Angular JS with a nested dictionary is a breeze

As a newcomer to AngularJS, I am facing an issue with my code. I have created a dictionary in the controller scope and populated it after an HTTP request (key, value pair). The dictionary is being created successfully and there are no errors, but the HTML ...

How can I prevent emailjs from submitting empty fields in an HTML form?

I recently created a form with an onclick event that triggers the submission of the form even if it's empty. Here is an example: <form> <div class="form-item"> <label for="date">Date:</label> ...

Verify all inputs are complete in the FullScreenForm

I have been working on implementing a form from this website: http://tympanus.net/Development/FullscreenForm/ My main objective is to validate each input when the form is submitted and display any errors that may arise. To achieve this, I have already se ...

Tips on choosing vml elements using jquery or vanilla javascript

I am trying to select a VML element using jQuery without relying on 'id' or 'class', but my attempts have been unsuccessful so far. <v:oval id="vmlElement" style='width:100pt;height:75pt' fillcolor="red"> </v:oval> ...

Guide on utilizing nested arrays in Gatsby using ReactJS and GraphQL

One of my components, menu.js, is imported into a page to display a list of articles that can be filtered by category, and it works as expected. Now, I want to modify the component so that I can filter the articles by tags. The issue is that the tags are ...

What is the best way to retrieve data from the next page in a Protractor test?

I am currently in the process of automating the test for booking a flight. When I enter the credentials on the homepage, click the Submit button, and the browser navigates to the search results page. const EC = protractor.ExpectedConditions; describe( ...