Incorrect results are being returned while iterating through an array

When comparing a variable with an array, specifically $scope.object.id and $scope.groepen.id, I am using an if statement following a for loop. If $scope.object.id matches any of the IDs in $scope.groepen.id, then the corresponding index of $scope.overlap should be set to true.

I also have another if statement to check if any elements in $scope.overlap are true. If at least one element is true, then $scope.bestaand is set to true; otherwise, it is set to false.

for (var i = 0; i < $scope.groepen.length; i++) {
  if ($scope.object.id === $scope.groepen[i].id) {
    $scope.overlap[i] = true;
    if ($scope.overlap[i]) {
      $scope.bestaand = true;
    }
    else {
      $scope.bestaand = false;
    }
  }
  else {
    $scope.overlap[i] = false;
  }
}

The console log confirms that $scope.overlap displays the correct values (all indexes are false when no match is found). However, the issue arises when $scope.bestaand remains true even when no match is found.

To validate this behavior, Angular form validation is applied as shown below:

<div class="col-md-3" ng-class="{ 'has-error' : bestaand }">
    <label class="control-label" for="textinput">Groepsnaam</label> 
    <input id="groepen" name="groepen" type="text" class="form-control input-md" ng-model="object.id" ng-minlength="4" ng-maxlength="16" ng-change="checkOverlap()" required>
    <p ng-show="bestaand" class="help-block">Deze groepsnaam bestaat al!</p>                            
</div>

What mistake could be leading to this behavior?

Edit:

I reorganized the placement of my if statements. Updated code is shown below:

for (var i = 0; i < $scope.groepen.length; i++) {
  if ($scope.object.id === $scope.groepen[i].id) {
    $scope.overlap[i] = true;
  }
  else {
    $scope.overlap[i] = false;

  }
  if ($scope.overlap[i]) {
      $scope.bestaand = true;
      console.log("works")
  }
  else {
    $scope.bestaand = false;
    console.log("doesnt work")
  }
}

The console log reveals the following results:

https://i.sstatic.net/0GOkY.png

It appears that the value does become true, but it gets overwritten (when using a value matching the second item in the array). However, if a value matching the last item in the array is used, it works correctly.

Answer №1

The issue lies in how you've nested if ($scope.overlap[i]) { within

if ($scope.object.id === $scope.groepen[i].id) {
, causing $scope.overlap to always be true. This results in $scope.bestaand being either set to true or left as undefined. What you actually need is -

for (var i = 0; i < $scope.groepen.length; i++) {
  if ($scope.object.id === $scope.groepen[i].id) {
    $scope.overlap[i] = true;
  }
  else {
    $scope.overlap[i] = false;
  }
  if ($scope.overlap[i]) {
    $scope.bestaand = true;
  }
  else {
    $scope.bestaand = false;
  }
}

Edit If you want to set $scope.bestaand to true if any of your $scope.overlap elements is true, then you'll need something slightly different -

$scope.bestaand = false;
for (var i = 0; i < $scope.groepen.length; i++) {
  if ($scope.object.id === $scope.groepen[i].id) {
    $scope.overlap[i] = true;
  }
  else {
    $scope.overlap[i] = false;
  }
  if(!$scope.bestaand) {
    if ($scope.overlap[i]) {
      $scope.bestaand = true;
    }
  }
}

Answer №2

The reason why the else statement is unreachable is because:

$scope.overlap[i] = true;

if ($scope.overlap[i]) {
  $scope.bestaand = true;
}
else {
  console.log('UNREACHABLE');
  $scope.bestaand = false;
}

In regards to your updated query:

If your $scope.bestaand indicates an error, it should remain false if set once.

To achieve this behavior, you should modify your loop as shown below:

$scope.bestaand = false;
for (var i = 0; i < $scope.groepen.length; i++) {
  if ($scope.object.id === $scope.groepen[i].id) {
    $scope.overlap[i] = true;
  } else {
    $scope.overlap[i] = false;
  }

  if ($scope.overlap[i] && !$scope.bestaand) {
    $scope.bestaand = true;
  }
}

Answer №3

There will be no instance where you assign it as false. If the condition

if ($scope.object.id === $scope.groepen[i].id)
evaluates to true, then you have already assigned overlap = true. If overlap remains false, there is never a scenario where you assign bastaan = false

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

Magnify the picture based on the given coordinates x and y

There is an image with a "ruler" made of basic divs positioned absolutely on top of the image to measure its ends. The concept is that if you long press one end of the ruler (the draggable dots at the line's end), the background image would zoom in at ...

Attempting to retrieve the numerical value displayed on my range slider. (using Bootstrap 4 and JavaScript)

var slider = new Slider('#slider1',{ tooltip: 'always' }); //generate a password function passwordGenerator () { // how long is the password going to be? var passwordLength = document.getElementById('slider1').value; ...

Wordpress woes: When Ajax fails to yield a successful result

I am facing an issue where I am trying to retrieve a return value from an AJAX call when the database gets updated. The data is being sent through AJAX to a function located in functions.php within one of the Wordpress plugins' folders. However, whene ...

Ways to conceal a button using Javascript

Due to my limited JavaScript experience, I am struggling with understanding the event flow. This was written in haste, and further editing may be needed. I am working on creating a stack of cards (Bootstrap cards) along with a load button. To keep it inde ...

Automatic closure of Info Window on Google Maps is not functioning as expected

I have recently developed a map which you can view here. The issue I am facing is that when I click on the layers to see the InfoWindow, they do not automatically close when I click on another layer. The JavaScript code I am using is causing this problem. ...

Encountering a 500 error in API Connect while trying to incorporate basic Javascript functionality

Currently, I am following some basic API Connect tutorials on IBM's platform. I am running these tutorials locally using Loopback, but I have hit a roadblock at an early stage. Initially, I created a simple API service with some in-memory data and se ...

Unspecified data returned from PHP script via jQuery AJAX

Encountering an issue while trying to use AJAX to get a PHP response from a form. The JavaScript appears to be correct as it functions when the content of login_ajax.php is reduced to just: echo 'CORRECT' //or echo 'INCORRECT' Howev ...

Is there a way I can retrieve a set of data from a JSON file by simply clicking on the next or

I am currently working on building a Hybrid mobile app using Angular and Ionic frameworks. Below is the sample data that I have obtained: $scope.data = [{ "PID": 108, "Name": "Demo", "TID": 20, "date": "2016/00/29" }, ...

Refreshing the dropdown selection to a specific option using AngularJS and either JavaScript or jQuery

Currently, I am facing an issue with resetting the select tag to its first option. I have implemented Materialize CSS for styling purposes. Despite my efforts, the code snippet below is not achieving the desired outcome. Here is the JavaScript within an ...

"Encountering an error: invalid CSRF token in Node.js csurf

I have been utilizing the npm module csurf to generate a token. Initially, I retrieve the token from the server and then utilize it for the /register request. When I replicate these steps in Postman, everything seems to function correctly, but unfortunatel ...

How Should One Properly Describe an Object with Multiple Dimensions?

PHP features multidimensional arrays, meaning an array that contains multiple arrays within it. When working with JavaScript, how does one refer to an object that holds multiple objects? Is it called a multidimensional object or is there a different termi ...

After running the command "npx/npm create-react-app hello" to create a react app, I received the following message

Whenever I try to execute this command for creating a React app: C:\WINDOWS\system32> npm i create-react-app -g hello I receive the following message in my cmd prompt: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf ...

Join the tournament for a thrilling game of Battleship in 1 dimension. We will keep track of all your moves using an array, comparing them to your latest input for

As a beginner programmer, I have recently delved into learning JavaScript on my own. One of the projects I tackled was creating a simple battleship game. However, I encountered an issue where if the user hits the same location three times, the battleship s ...

Develop a reusable method/function within a JavaScript class for future use

I encountered an error message stating React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. I am trying to create a public method within a class so that I ca ...

AngularJS is throwing an error stating that the URL ID is undefined

I am developing an application that utilizes angularjs with codeigniter as the backend. Within my URL, I have http://localhost/submit/1234, with 1234 serving as the ID. Within my angularjs setup: var singlepost = angular.module('singlepost', [ ...

Data not reflecting changes in component when field is modified?

I currently have a table on my web page that displays data fetched from an array of objects. The data is collected dynamically through websockets by listening to three different events. User can add an entry - ✅ works perfectly User can modify ...

Having difficulty in animating the upward movement of textbox2

I've got a form that contains 2 buttons and 2 textareas. When the form loads, I want to display only section1 (button, textarea) and the section2 button. Upon clicking the section2 button, my aim is to hide the section1 textarea, reveal the section2 t ...

The jsonGenerator is unable to process strings containing spaces

Hey, I'm having trouble passing a string with whitespaces to my JavaScript function using jsonGenerator. Here's the code snippet: jGenerator.writeStringField(cols[8], ap.getContentId() != null ? "<img src='img/active.png' onclick=au ...

What causes the interference of one Import statement with another?

In the JavaScript file I'm working with, I have added two import statements at the beginning: import { FbxLoader } from "./ThreeJs/examples/jsm/loaders/FBXLoader.js"; import * as Three from "./ThreeJs/src/Three.js"; However, when ...

Managing the hovering of a mouse over an image within an isometric grid displayed on a

I have implemented an isometric grid in HTML canvas. My goal is to handle mouse hover events on the buildings within the grid. Some buildings will vary in heights. In the image below, you can see that when hovering over a tile, the highlighted area shif ...