Storing string variables within an array and subsequently evaluating the similarity of each variable's value with those stored within the array

I am currently working on an Angular page which consists of input fields where I capture and store values in variables within the .ts file. The entered values are subject to change, so hard-coding them is not feasible.

The variables that I use for storing these values are associated with [(ngModel)] for effective data binding. Everything works smoothly as the values get stored properly.

input1_1: string;
input1_2: string;
input2_1: string;
input2_2: string;

To streamline the comparison process, I group the inputs ending with _1 into the fromArray, while those ending with _2 go into the toArray.

My goal is to ensure that no value from fromArray exists in toArray. To achieve this, I attempted the following logic:

if (this.toArray.includes(this.input1_1) == true) {
//disable the next button
}

However, this approach did not yield the desired result. It appears that I need to access actual values instead of references for accurate comparison.

How can I efficiently compare whether the array of variables holds the same value as a different variable?

Here's all the code consolidated together (extracted for illustrative purposes), which should provide more clarity.

// Input values from Angular HTML input fields
input1_1: string;
input1_2: string;
input2_1: string;
input2_2: string;
input3_1: string;
input3_2: string;
input4_1: string;
input4_2: string;

// Arrays for comparison
fromArray = [this.input1_1, this.input2_1, this.input3_1, this.input4_1];
toArray = [this.input1_2, this.input2_2, this.input3_2, this.input4_2];

// Function to execute for each input field
checkValues() {
  if (this.toArray.includes(this.input1_1) == true) {
    this.disableNext = true
  } else (this.disableNext = false)
}

In lieu of extensive comparisons between values, I opted for a concise approach. Despite scouring for similar examples for the past two hours, none proved helpful. While I did come across array.some(), I deemed array.includes() as a preferable option over it.

Any suggestions or guidance would be highly appreciated, especially since I'm relatively new to coding—feel free to seek clarification if needed.

EDIT: In response to requests from Jo Carrasco and Dev, I will include the complete setup:

StackBlitz link

Despite inaccuracies in html formatting on StackBlitz, it fulfills the necessary functionality.

The

this.toArray.includes(this.input1_1)
pertains solely to the first dropdown function (checkDropDown1) at present; extending it to others isn't warranted since my current focus involves checking just one.

You'll notice the disabled logic for the Next button, which mandates the entry of all values when the checkbox is ticked—disabling the button upon detection of similarities in either of the locations (i.e., similarity between values in either of the two dropdowns or any of the input fields).

EDIT 2

Evidently, the array values fail to update dynamically post initial assignment. It retains the original value assigned to the variable without reflecting subsequent edits made to the variable (input field).

-- To address this issue, I began splicing array values. Consequently, whenever I invoke a function tasked with checking the array values, I remove the existing value and insert the updated value into the array before conducting a comparison using an if statement nested inside a for loop. This method replaces the original array.include(); with a check denoted by equalValue.

this.fromArray.splice(0, 1, this.input1_1);
this.toArray.splice(0, 1, this.input1_2);

var equalValue = false;

for (let i = 0; i < this.toArray.length; i++) {
  if( this.toArray[i] === this.input1_1) {
    equalValue = true;
    console.log(this.toArray[i]);
    console.log(this.input1_1);
    break;
  }

}

If you have a more efficient solution, please share it—I'll evaluate it and acknowledge it if it indeed resolves the issue better.

Answer №1

To help us troubleshoot the issue, please provide the code for us to test ourselves. It seems that the string properties are not defined.

undefined == true //false

This might be why you are unable to retrieve the correct value

Here is a suggestion on how to attempt it:

if (this.toArray.includes(this.input1_1)) {

Answer №2

If you're not concerned about the exact value, but want to ensure that toArray and fromArray do not contain any duplicate values, here's a solution for you: Include lodash in your project - https://lodash.com/docs/4.17.15#uniq

checkValues() {
  if (_.uniq([...this.toArray, ...this.fromArray]).length < [...this.toArray, ...this.fromArray].length ) {
    this.disableNext = true
  } else (this.disableNext = false)
}

Explanation: If both arrays have some values in common-

this.toArray = [a,b,c];
this.toArray = [a,b,d];
[...this.toArray, ...this.fromArray] will equal [a,b,c,a,b,d] // length will be 6
_.uniq([...this.toArray, ...this.fromArray]) will equal - [a,b,c,d]; // length will be 4
// If duplicates are present, the left side will be less than the right side in the if statement

If both arrays have no shared values-

this.toArray = [a,b,c];
this.toArray = [d,g,f];
[...this.toArray, ...this.fromArray] will equal [a,b,c,d,g,f]  // length will be 6
_.uniq([...this.toArray, ...this.fromArray]) will equal - [a,b,c,d,g,f]; // length will be 6
// In this case, it will go to the false condition 

Hope this explanation helps! Happy coding!! :)

Answer №3

To resolve the issue, I made a modification to how I handle array values. Whenever a function needs to check the values in the array, I first remove and then insert the value that requires updating into the array. I then compare the values using an if statement within a for loop. The actual comparison is done inside the if statement with the use of equalValue, replacing the intended array.include();.

checkValues() {
  this.fromArray.splice(0, 1, this.input1_1);
  this.toArray.splice(0, 1, this.input1_2);

 var equalValue = false;

  for (let i = 0; i < this.toArray.length; i++) {
    if( this.toArray[i] === this.input1_1) {
      equalValue = true;
      console.log(this.toArray[i]);
      console.log(this.input1_1);
      break;
    }

  }

  if (this.equalValue == true) {
    this.disableNext = true
  } else (this.disableNext = false)
}

If you have a more efficient solution, feel free to share it, and I will review and mark it as the answer if it provides a better resolution to the issue.

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

Angular Service Fails to Execute Upon Initial Loading

In my current project, I am utilizing Angular 9.0.7 with a Node.js (Express) backend and an Angular frontend. The issue I'm facing is that the service function responsible for fetching data from the backend is not being invoked on the initial page lo ...

Rearranging elements within an array using PHP

My array $myArray contains: Array ( [0] => Apple [1] => Orange [2] => Grape [3] => Plum ) The content of this array is dynamically pulled, but I require it to be in a specific order. For example, Grape should always be first, Plum second, App ...

I attempted to unsubscribe from an observable in Angular, but I encountered an error stating that the unsubscribe function does not exist

Here is the code snippet from a components.ts file in an Angular project. I encountered the following error during compilation: ERROR merge/merge.component.ts:75:12 - error TS2551: Property 'unsubscribe' does not exist on type 'Observable& ...

What is the process for using infer to determine the return type of a void function?

I am trying to gain a better understanding of how to utilize the infer keyword in TypeScript. Is this an appropriate example demonstrating the correct usage of infer? I simply want to infer the return type of the function below: const [name, setName] = u ...

There are no versions available for Angular NPM that match [email protected]

Here is the contents of my .npmrc file: registry=https://pkgs.dev.azure.com/<yourOrganization>/_packaging/<yourFeed>/npm/registry/ always-auth=true After deleting node_modules and attempting to install the packages, I encountered the follo ...

Sending data from a PHP array to a JavaScript array within a PHP function

I have been scouring Stack Overflow for a solution to my problem, but I haven't found one that fits my specific issue. I recently took over a project from a former coworker that involves managing all the videos and images for my company. My current di ...

Hiding collapsible navbar in Angular 7 when in responsive mode

Hey there, I'm currently using a navbar in Angular 7 and I'm looking for a way to collapse it when clicking on another area of the page. When resizing my browser or when accessing the app on mobile, the navbar displays a menu icon with three bars ...

Can I combine tuple types in Typescript?

type A1 = ['x','y','z'] type A2 = ['u','v','w'] type AN = [.., .., ..] type C = Combine<A1,A2,...,AN> //or Combine<[A1,A2,...,AN]> //resulting in ['x','y','z& ...

The Battle of Extends and Intersection in Typescript

Typescript's concept of extension is akin to C++'s inheritance. Intersection in Typescript involves creating a new object with all the properties from the intersected classes. Why utilize intersection when extends keyword can already merge ...

What is the top choice for creating a shallow copy of an array

While delving into the vue source code today, I stumbled upon a method of writing that left me puzzled. view source const deduped = [...new Set(pendingPostFlushCbs)] My initial thought is that it is a shallow copy of the array. But why is there a need t ...

A Guide to Implementing Inner CSS in Angular

I am working with an object named "Content" that has two properties: Content:{ html:string; css:string } My task is to render a div based on this object. I can easily render the html using the following code: <div [innnerHtml]="Content.html"& ...

Searching for multiple lines of text within a PHP document

Recently, I have been working on a project that involves an addon making modifications to a crucial system file. As part of this task, I have created a method to locate specific strings within the file: /** * @param $fileName * @param $str ...

having difficulty deactivating matInput within angular form

I am facing an issue with a form where I need to disable one of the inputs based on a certain condition. <mat-form-field> <input matInput formControlName="domain" [disabled]="!is_staff && recipients[selectedIndex].verified"> </m ...

Is there a way I can replace this for loop with the array.some function?

I am looking to update the filterOutEmails function in the following class to use array.some instead of the current code. export class UsertableComponent { dataSource: MatTableDataSource<TrialUser> createTableFromServer = (data: TrialUsers[], ...

NgOnChanges replaces form control value when user inputs text

In my autocomplete form control component: @Component({ selector: 'app-autocomplete', templateUrl: './app-autocomplete.view.html', changeDetection: ChangeDetectionStrategy.OnPush, }) export class AutoCompleteFilterComponent ...

Backend not receiving the request

While all tests pass successfully in Postman, I'm encountering an issue where requests are not reaching the backend when testing from the front-end. import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common ...

Identifying Errors in Meteor's Data Publications

I am currently working on a web application using Meteor and AngularJS 2. Take a look at the publication function below: Meteor.publish('abc', function () { // For throwing the meteor error according to the condition if(!this.userId) throw new ...

How can you ensure an interface in typescript 3.0 "implements" all keys of an enum?

Imagine I have an enum called E { A = "a", B = "b"}. I want to enforce that certain interfaces or types (for clarity, let's focus on interfaces) include all the keys of E. However, I also need to specify a separate type for each field. Therefore, usi ...

Angular encountering a 405 Method not allowed error along with the "Provisional Headers are shown" message

It's really frustrating me. I'm attempting to make a simple request to my api server by adding the header, but it keeps showing me the message "Provisional Headers are shown" and then fails on the subsequent request. Provisional headers are sho ...

Interacting between Angular Child and Parent components

I am facing an issue where I am trying to emit an event from a child component and display it in the parent HTML, but it doesn't seem to be working. Below is my code: ParentComponent.ts @Component({ selector: 'app-parent', templateUrl: ...