The string is being added to an array twice

I am managing two sets of lists where strings will be transferred between them.

One set contains a list of strings for searching purposes. The other set contains the same list of strings but is not used as a filter.

The second set functions in a similar manner, holding different strings.

Strings are moved between the two sets, ensuring that no string appears in both sets simultaneously.

The "deselectedListToBeMoved" stores the strings that need to be transferred from one set to another.

  selectCustomer() {
  for (let deselect of this.deselectedListToBeMoved) {
    this.deselectedList = this.deselectedList.filter(
      (customer) => customer !== deselect
    );
    this.originalDeselect = this.originalDeselect.filter(
      (customer) => customer !== deselect
    );
    this.selectedList.push(deselect);
    this.originalSelect.push(deselect);
  }
  this.selectedList.sort((a, b) => a.localeCompare(b));
  this.deselectedListToBeMoved = [];
}

*HTML*
 <div id="customer_{{cus}}" class="individual-customers" *ngFor="let cus of selectedList">{{cus}}</div>

An issue arises when calling this function, causing a string to be added to 'selectedList' twice at times, displaying it twice on the frontend.

If I remove the line: "this.originalSelect.push(deselect);", the string is only added to 'selectedList' once.

Answer №1

It is highly likely that the issue lies in the fact that you have:

this.originalSelect = this.selectedList;

// or something similar:
const array = [/* possibly some initial data */];
this.selectedList = array;
this.originalSelect = array;

What this means is that your two variables this.selectedList and this.originalSelect are actually pointing to the same object (array).

Therefore, any changes made to this object (such as using the .push() method) will be reflected in both variables since they are essentially accessing the same object.


If you wish for them to start off as identical but still be managed independently (while keeping their contents in sync, except for the order), you can create a shallow copy using the spread operator:

this.originalSelect = [...this.selectedList];

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

Exploring a Component's props and their data types

As a newcomer to React and Typescript, I have a straightforward question that I can't seem to find an answer to. I'm attempting to construct a tab layout using Typescript with headless UI following the documentation here I am encountering issue ...

Transforming JSON data into XML using Angular 7

It turns out the xml2js npm package I was using doesn't support converting JSON to XML, which is exactly what I need for my API that communicates with an application only accepting XML format. In my service file shipment.service.ts import { Injecta ...

Unable to find a solution to Angular response options

I'm having trouble saving an item to local storage when receiving a 200 response from the backend. It seems like the request status is not being recognized properly. options = { headers: new HttpHeaders({ 'Content-Type': &apos ...

Consolidate various arrays of objects while eliminating duplicate items based on an optional property

Imagine having multiple arrays like these: const arr1 = [ { "id": "1", "type": "sales" }, { "id": "2", "type": "finance" } ] const arr2 = [ { "type": "s ...

Exploring the sharing of observables/subjects in Angular 2

UPDATE: After further investigation, it appears that the SharedService is being initialized twice. It seems like I may be working with separate instances, causing the .subscribe() method to only apply to the initiator. I'm not sure how to resolve this ...

What methods can I use to integrate a Google HeatMap into the GoogleMap object in the Angular AGM library?

I am trying to fetch the googleMap object in agm and utilize it to create a HeatMapLayer in my project. However, the following code is not functioning as expected: declare var google: any; @Directive({ selector: 'my-comp', }) export class MyC ...

Steps to resolve the Angular observable error

I am trying to remove the currently logged-in user using a filter method, but I encountered an error: Type 'Subscription' is missing the following properties from type 'Observable[]>': _isScalar, source, operator, lift, and 6 more ...

Enhancing the theme using material-ui@next and typescript

While developing my theme using material-ui, I decided to introduce two new palette options that would offer a wider range of light and dark shades. To achieve this, I extended the Theme type with the necessary modifications: import {Theme} from "material ...

Is there a way to customize the Color Palette in Material UI using Typescript?

As a newcomer to react and typescript, I am exploring ways to expand the color palette within a global theme. Within my themeContainer.tsx file, import { ThemeOptions } from '@material-ui/core/styles/createMuiTheme'; declare module '@mate ...

I'm puzzled as to why I am unable to invoke a class method within this callback function. The error message indicates a TypeError: 'this' is undefined

Currently, I am troubleshooting a challenge in my Angular application that involve TypeScript. The issue lies within a method in a TypeScript class: findArtistBidsAppliedByCurrentWall(bid):Observable<Bid[]> { console.log("findArtistBidsApplied ...

What is the best way to restrict a mapped type in typescript to only allow string keys?

In the Typescript documentation, I learned about creating a mapped type to restrict keys to those of a specific type: type OptionsFlags<Type> = { [K in keyof Type]: boolean; }; If I want to use a generic type that only accepts strings as values: t ...

What is the best way to identify a particular subtype of HTMLElement based on its tag name and then save that element within another one?

I have a function that generates a node and returns it. Here is an example implementation: addElement: function ({ parentNode, elementName, tagName, }) { // Creates and appends the new node. parentNode[elementName] = document.createEl ...

Multiple invocations of the callback function in an Angular5 template binding

In trying to create a grid component that uses structured data containing definitions for columns and an array of data. Each column definition includes a callback function to customize the display of that specific column's value. Within each callbac ...

Receiving an error with React Proptypes when using the union type Breakpoint

Struggling to assign the correct proptype to the material-ui Breakpoint type. The breakpoint values are: export type Breakpoint = 'xs' | 'sm' | 'md' | 'lg' | 'xl'; In my App.tsx file, I have the following ...

issue with global variable not functioning properly within a sub-function in Angular 7

I have a question that needs clarification import { Component, OnInit,ViewChild,ElementRef } from '@angular/core'; import {Http,Headers} from "@angular/http"; import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, ...

I have noticed that my unit test case does not include coverage for the if statement

Here is the function I have in my TypeScript file: routeToIndividualPortal(sessionToken: string) { let redirectUrl = this.relayState; console.log("Pre-source-check Indivual URL : " + redirectUrl); let url = ""; if(redirectUrl.includes(this. ...

Error: The layout was unable to display the template body

I've been working on a web application with express and eta, but I'm running into an issue with including partials in my templates. Despite trying to include a file partial (refer to the Docs), the compiled template doesn't seem to incorpor ...

Exploring the implementation of Generic types within a function's body

When trying to encapsulate logic inside the OrderGuard component (which can handle two types of orders: CheckinOrder or Checkout order), I encounter an issue when passing the order to the orderLoad callback in TypeScript. The error message states that "Ch ...

What is the best approach to integrating payment solutions into a React Native application running on version 0

Seeking advice on integrating payment systems in React Native 0.70. Previously utilized react-native-credit-card-input and react-native-credit-card-input-plus with earlier versions, but they are now incompatible. ...

Trigger a response according to the information received from the preceding action

I'm facing an issue with dispatching actions in sequence after the completion of the previous one. My goal is to dispatch an action (let's call it getDetails), use the data from this action to dispatch another action (getUserLists), and finally ...