The condition to break when a value is found within a specific range on sheet1 if it is present in the range on

Essentially, the user will input data for a new item on the NovoItem sheet. Upon pressing the Save Button (yet to be added), the code should check the ArquivoItens sheet to see if the item already exists. If it does, the code should halt its operation. However, currently, the code is not halting when a match is found on the ArquivoItens sheet:

function copyrange() { 
  var sourceSheet = 'Novo Item';
  var destinationSheet = 'ArquivoItens';
  var ss = SpreadsheetApp.getActiveSpreadsheet(); 
  var sheet = ss.getSheetByName(sourceSheet);
  var ActiveUser = Session.getActiveUser();

  //This part adds the current user and a timestamp to the last two columns of sheet1.
  var val = sheet.getRange("Q12:Q")
      .getValues();
  for (var i = 0; i < val.length; i++) {
      if (val[i] > 0) {
        sheet.getRange(12, 34, i + 1, 1)
               .setValue(new Date());
       sheet.getRange(12, 35, i + 1, 1)
               .setValue(ActiveUser)
      }
    }

  var LastRowSource = sheet.getLastRow();
  var LastColumnSource = sheet.getLastColumn();
  var values = sheet.getRange(11,1,LastRowSource,LastColumnSource).getValues();
  var csh = ss.getSheetByName(destinationSheet);
  var data = []; 

  for (var i = 1; i < values.length; i++) {    
    if ( values[i][0] != '') { 
      data.push(values[i]);      
      //sheet.deleteRow(i+1) 
    } 
  }

  var dataNovoItem = sheet.getRange("B12:B").getValues(); 
  var dataArquivoItens = csh.getRange("B2:B").getValues(); 

  for(var n=1; n < dataNovoItem.length ; n++){
    for(var j=1; j< dataArquivoItens.length ; j++){
      if (dataNovoItem[n] != 0 && dataArquivoItens[j] != 0) {
        if(dataNovoItem[n] == dataArquivoItens[j]) {
        break;
        }
      }
  }
    }

  Logger.log("Novo Item" + dataNovoItem);
  Logger.log("ArquivoItens" + dataArquivoItens);

  //Copy data array to destination sheet  
 csh.getRange(csh.getLastRow()+1,1,data.length,data[0].length).setValues(data);

}

Here's the log output I'm seeing: https://i.sstatic.net/Zdp8T.jpg

Any assistance would be greatly appreciated.

Answer №1

Make sure to utilize the iterator correctly in order to access the index being iterated through.

Try this instead:

for(var i=0; i < newData.length; i++){
    for(var j=0; j < oldData.length; j++){
        if (newData[i] !== 0 && oldData[j] !== 0) { 
            if(newData[i] == oldData[j]) {
                break;
            }
        }
    }
}
Logger.log("New Data: " + newData);
Logger.log("Old Data: " + oldData);

Answer №2

My solution involved iterating through the current list and comparing each row with the specified value on the active sheet. While this may seem straightforward to experienced programmers, it presented a challenge for someone like me who is still a beginner.

Here’s how the process looks now:

var newItemID = sheet.getRange("W5").getValue(); // Obtain the cell where the new item will be placed
var itemIDArquivoItens = csh.getRange(2, 1, csh.getLastRow(),1).getValues(); // Retrieve the range of existing IDs to compare against

var message = "Item already registered!"; // Displayed message if the ID already exists in the list
for(j = 1; j < itemIDArquivoItens.length; j++) { // Loop through existing IDs
  if(itemIDArquivoItens[j][0] == newItemID) { // If the ID exists, show a message and halt the code execution
    Browser.msgBox(message)
    return;
  }
}

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

Preventing runtime error in Next.js API routes by handling axios exceptions

I am currently working on creating an API route in Next.js that sends a request to my backend and saves the token in the cookies. However, I am facing an issue where 4xx responses are causing an Unhandled runtime error. Despite everything working correctly ...

Maximizing the efficiency of React.js: Strategies to avoid unnecessary renders when adding a new form field on a webpage

Currently, I have a form that consists of conditionally rendered fields. These components are built using MUI components, react-hook-form, and yup for validation. In addition, within the AutocompleteCoffee, RadioBtnGroup, and TxtField components, I have i ...

Tips for implementing Bootstrap pagination in VueJS 2

Here is how my website appears: Jobs.vue: <div id="jobs" class="job-item" v-for="(item, index) in showJobs" :key="index" > <router-link ...

Utilize emit to distribute / allocate a variable

I have some variables stored in a file called server.js (and they tend to change frequently). My goal is to pass these variables to client.js whenever the client sends a request (triggers the 'validate' event). Even though the event is triggered, ...

showing a fading-in effect after a successful AJAX post

Maybe a simple question, but I've been struggling to make this work for quite some time now. Despite trying various solutions from stackoverflow, I can't seem to get it right. Perhaps fresh eyes could help me figure out how to achieve this. My g ...

Storing the result of an Angular $http.get request in a variable

As a newcomer to Angular, I am exploring how to retrieve a JSON object containing a list of individuals from CouchDB using a $http.get call. The JSON structure includes an id, names, and quotes for each person: { "total_rows": 2, "offset": 0, ...

Tips for executing parallax designs, similar to the techniques used on the

Currently, I am in the process of creating a website that utilizes parallax scrolling. Here is a brief overview of what I have accomplished thus far. I decided to use the skrollr plugin to achieve the desired parallax effect. Through this plugin, I was abl ...

Error message in the browser console: Uncaught TypeError - The function allSections.addEventListener is not recognized

Whenever I inspect my browser console, I keep encountering this error: Uncaught TypeError: allSections.addEventListener is not a function at PageTransitions (app.js:16:17) at app.js:33:1 I find it strange because my VS Code editor does not display any err ...

Saving integer data retrieved from DynamoDB in a React Native application

I need to store a user's progress by saving a value in a DynamoDB. While storing the value is not difficult, accessing this value for use in my application has proven to be quite challenging. When using dynamoDBWrapper.getItem(params), where the para ...

How can you update the options within a select tag depending on the selected index of another select tag using AngularJS?

Consider the following code snippet: $scope.letters = ['A', 'B', 'C', 'D']; $scope.numbers = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]; $scope.selectedLetter = 0; There are two select tags in t ...

Here is a unique version: "In Javascript, users can trigger the function this.Something() from within this.img.onload by

I have some code that looks like this... Thing function () { var img = new Image; DoSomeStuff function() { //Code here that relies on my image being loaded... }; InitMe function(src) { this.img.onLoad = this.DoSomeStuff; ...

IntelliJ coverage for backend JavaScript

Is it possible to analyze code coverage in IntelliJ without using a browser? http://www.jetbrains.com/webstorm/webhelp/monitoring-code-coverage-for-javascript.html Though there are tutorials by JetBrains on code coverage, they all seem to require a browse ...

Breaking down a string and then retrieving elements from an array

Just diving into the world of Javascript and jQuery, so I have a simple query. I've got a date that I need to break down into a string and then display it as an array. var date = "12/10/2010"; var dateArray = date.split(/); $('#printbox') ...

The split() function returns a string that remains unaltered and intact, without any

I am attempting to separate this string: 120,00 m² into two distinct parts like this: 120 m² This is the code I have been using: var test = jQuery('#wpsight-listing-details-3 .span4:nth-child(4) .listing-details-value').html(); var pa ...

Object contains a key within another object

I have an array of objects, each containing another object. I want to check if a specific key exists within the inner objects. var myarr = [{ hello: "world", payload: { kekek: 'sdfsdfsdf', baby: 'sdfsdfsdfds&apo ...

What is the best way to distribute a function within a div container?

I'm currently working on a function that manages the show/hide functionality and position of tooltips: tooltip = (e) => { // show/hide and position of tooltip // retrieve element data } In addition, I have div elements whe ...

Javascript does not have the capability to interact directly with HTML code

I am facing an issue with my JSP code that is supposed to validate password and confirm password before submitting the form to a Java servlet. The problem is, even though I have written the validation script, it does not show alert messages or focus on t ...

Distinguishing between el and $el in Backbone.Js: What sets them apart?

I spent the entire afternoon struggling with this particular issue, but finally managed to resolve it. It ended up being a mix-up between assigning el and $el. Can anyone clarify the distinction between these two terms and provide guidance on when to use ...

Using Passport authentication callback rather than redirecting the user

passport.authenticate('local-register',{ successRedirect: '/login', failureRedirect: '/path_to_greatness', })(req, res, next); In the process of developing a stateless API, I have encountered l ...

What is the best way to expand this HTML5 canvas script to fill the entire screen?

I am having issues adjusting the canvas to fill the entire window. Currently, it is set to 500x500. As a beginner in coding, any assistance would be greatly appreciated! Thank you. Below is the code snippet: <!DOCTYPE html> <html> <head& ...