Pause and Persist

Can someone help me clarify a code issue I'm facing? I have a piece of code that checks an array for overlapping values based on different criteria. This code specifically deals with rows and columns in a Google Sheet using GAS. Here's what I currently have:

  var e = [[2,4,3,4,2],[1,5,3,6,2],[2,4,3,4,1],[1,4,3,6,1],[2,4,3,6,5]];
  var i; //id of entry to check
  var j; //id of element to check
  var k; //id of entry to compare

  for (i in e){ //2D ARRAY ARRAY
      for (k in e){ //ELEMENT TO COMPARE
           if (e[i][2] === e[k][2] && e[i][3] === e[k][3] && e[i][0] && e[i][0] >= e[k][0] && e[i][1] <= e[k][1] && e[i][4] <= e[k][4] &&  i !=k){
             e.splice(i,1);
             continue;
           }
      }
  }
  return e;

I had to include the continue; statement because without it, the code failed when the last array was also marked for removal using `splice`. I initially thought using break instead of continue would solve the issue, but it didn't work as expected. Does break permanently stop that specific section of code?

Thanks in advance

EDIT: Scratch that, the code still doesn't work even with `continue`. Still trying to figure this out!

Answer №1

continue instantly goes to the next iteration, for example:

  while(true) {
    console.log("a");
    continue;
    console.log("b");
 }

only "a" will be logged because it would jump back to the beginning of the loop whenever it encounters continue. Placing continue at the end of the loop (similar to your code) results in no action, just skipping an empty line.

I assumed break would exit to the outer loop

Indeed, that's what happens, and it is beneficial as there's no need to check for duplicates if the element has already been removed; removing it twice wouldn't make sense.

The issue arises when splice alters the indexes. If you remove the fourth element, the fifth one becomes the fourth one, but the loop continues to the fifth element without revisiting the fourth (which is now different). Thus, you should backtrack by one element before breaking out of the loop:

 for(let i = 0; i < e.length; i++) {
   for(let k = 0; k < e.length; k++) {
      if(i === k) continue; // < appropriate scenario
      if(/* condition checks */) {
        e.splice(i, 1); // remove the element
        i--; // go back one position due to reordering
        break; // exit inner loop
     }
   }
 }

In my opinion:

1) I prefer using

for(const [i, value] of arr.entries()
over for..in

2) Naming indexes properly makes code more readable than having to remember what arr[i][2] represents:

  const [idA, someValueA] = e[i];
  const [idB, someValueB] = e[k];
  if(idA === idB && someValueA <= someValueB // ...

3) Using a better variable name than e is advisable.

Answer №2

To escape from nested loops, you can utilize a labeled break statement. For example:

var count = 0;
mainLoop:
for(var x = 0; x < 10; x++){
  for(var y = 0; y < 10 ; y++){
    if(x == 5 && y == 5){
      break mainLoop;
    }
    count++;
  }
}

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

Extracting data with Jquery Repeater in jQuery

A repeater has been implemented using html/js, utilizing this helpful library. Currently, the goal is to extract data upon user clicking a button (work in progress). However, the challenge lies in accessing the data within elements like ingredienten[0][wa ...

Ways to verify the existence of a particular word within a nested array of objects

I have implemented a text input field and a send button for submitting the entered text. Utilizing the react-mention library, I am able to handle hashtags in the text. As the user types, if they include "#" it displays available hashtags from the data set. ...

What is the best way to retrieve data from PHP and format it into JSON for use in my jQuery script?

I need help formatting the data returned to jQuery from a query. The specific format I want is: var externalDataRetrievedFromServer = [ { name: 'Bartek', age: 34 }, { name: 'John', age: 27 }, { name: 'Elizabeth', ...

Obtaining a cookie from a browser that has been dropped by a different application

Is there a way to check if a user is logged in by hitting an application URL programmatically using Java or JSP? It generates a cookie named xyz for logged-in users in the browser. For some reason, every time I call the URL from my Java code, it doesn&apo ...

if a user does not click on an element in jQuery

Looking for a clever jQuery trick to determine if something other than a specific element (and its descendants) was clicked? <body> <header></header> <p>stuff<p> <div class="floating-form"> <form>more st ...

Storing a table structure in a variable using JavaScript

Kindly review this arrangement: 1 | 2 | 3 | .... ---------------------------------------------------------- 2016 100 2000 500 2015 540 450 1200 2014 120 230 660 I am seeking a method ...

Tips for arranging years in descending order in the material-ui Date Picker's calendar interface

This is the Code I Used - import "./styles.css"; import { DatePicker } from "@mui/x-date-pickers"; import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider"; import { AdapterDateFns } from "@mui/x-da ...

Unable to generate a fresh directory with mongoose and express

As the title suggests, I am working on an application that generates a link using mongoose _id and express's app.get when certain information is inputted. However, I am facing an issue where I have to reload the entire server in order to access the di ...

The challenges encountered with JSONP/Ajax Script - displaying 'Undefined'

I need help retrieving data from a webserver that I don't have control over. I've searched online but haven't found a solution yet. I've tried various codes, with and without DataTables. If anyone could provide guidance on where to go ...

Tips for transforming a hover menu into a clickable menu

The scenario above demonstrates that when hovering over the dropdown menu, it displays a submenu. However, I want the submenu to be displayed after clicking on the dropdown text. Could anyone provide assistance on how to change the hovermenu to a clickabl ...

Get the value of the button that has been clicked

I have a query regarding building a website that can be started via PowerShell. The PowerShell HTML code I am using is: $proxys = "" foreach ($email in $ADObj.proxyAddresses){ $proxys += "<button id='$email' name='alias&apo ...

The error message keeps appearing consistently. What is the best way to manage this error?

Even after entering the data in this field, it was supposed to disappear. However, that didn't happen as expected. <md-input-container class="md-block" flex-gt-sm> <label>Budget</label> <input name="budget" ng-model="newTri ...

What is the best method for sending a JavaScript variable to the server and back again?

I'm currently working on a JavaScript project where I need to build a string. Let's say, for the sake of this example: var cereal = 'my awesome string'; There's also a button on my webpage: <button id="send" type="submit" nam ...

I'm experiencing issues with my AJAX as it fails to post or respond after the user clicks on the submit

I am currently working on implementing a list of events, each with a tick box and an x box for marking the event as complete or deleted. The challenge I'm facing is that when I click the buttons, nothing happens without refreshing the page. I suspect ...

Transferring map functionality to a separate file

Is it possible to export the function inside the orders.map, specifically 'order', and then import it into another JS file with a function inside? I keep receiving an error that order is not defined. Thank you main.js const getReport = asy ...

Monitor changes in the select tag to display the updated value and output

I am new to using jQuery. While I have practiced using native PHP Ajax in the past, I now recognize the need to learn jQuery due to current technological advancements and demands. When the select tag changes, I send the "types" value via POST method to a ...

Is there a way to properly dissect or iterate through this?

I have exhausted all possible methods to retrieve the data, but I am unable to solve this puzzle. The information is organized in a format like the following: [{"code":1000,"day":"Sunny","night":"Clear","icon":113,"languages": [{"lang_name":"Arabic","lan ...

Using javascript to eliminate a block of HTML code

In my AngularJS project, I am using owl-carousel and attempting to reinitialize the carousel after a change in data by using $(element).data('owlCarousel').destroy(); while also removing this block: <div class="owl-wrapper"> <div class= ...

Invoke the method in customButton component of fullcalendar

I've integrated a custom button into my fullcalendar: ngOnInit() { this.calendarOptions = { customButtons: { custom1: { text: 'Add event', click() { this.openModal(); } } }, height: 600, editable: t ...

Redirect based on the geographical location of IP addresses (Geo-IP)

This code displays the page during execution and then initiates a redirect. Unfortunately, the redirection process is not as fast as desired. This application was created on blogspot.com <script> fetch('https://freegeoip.app/ ...