The push() method replaces the last item in an array with another item

Two objects are available:

ej= {
    name="",
    code: "",
    namebusinessG:"",
    codebusinessG:""
};  
group = {
    name:"",
    code:""
}

Both of these objects will be stored in two arrays:

groupList:any[]=[];
ejList:any[]=[];

The program flow should follow these rules:

  • When a group is added to groupList: Check if the group already exists in groupList, if not, add it.

  • When an ej is added to ejList: Check if the ej already exists in ejList, if it does not exist, add it. Then, the program should add ej.codebusinessG and ej.namebusinessG to groupList. However, it must first verify beforehand if ej.codebusinessG already exists in the list of groupList.code, and only then add it.

    selectItem(event) {
        if (!this.toggle) { // in group
            if (this.groupList.length == 0) {
                this.groupList.push(event);
            } else if (this.testNotExistinginArray(event, this.groupList)) {
                this.groupList.push(event);
            }
    
        } else { //in ej
            if (this.ejList.length == 0) {
                this.ejList.push(event);
                if (this.groupList.length == 0) {
                    this.groupList.push({
                        code: event.codebusinessG,
                        name: event.nameBusinessG
                    });
                }
            } else if (this.testNotExistinginArray(event, this.ejList)) {
    
                this.ejList.push(event);
    
                this.group.code = event.codeBusinessG;
                this.group.name = event.nameBusinessG;
                if (this.testNotExistinginArray(this.group, this.groupList)) {
                    this.groupList.push(this.group);
    
                }
            }
        }
    }
    

A function is provided for testing whether a code exists in an array or not:

testNotExistinginArray(event,type) {

    let notExist=true;
            type.forEach (function(elm) {
                if(elm.code === event.code) {
                    notExist=false
                }
            })
    return notExist;
}

Current behavior

Adding Group: verification + addition OK

Adding ej: verification + addition OK

However, after adding the third ej, the corresponding group overwrites the last item in groupList instead of being added after it.

Here's a breakdown of what happens:

First ej is added (both ej and group are successfully added)

https://i.sstatic.net/Rrw1H.png

Second ej is added (again, both ej and group successfully added)

https://i.sstatic.net/l0HaE.png

Finally, the third ej is added...

https://i.sstatic.net/gLdBe.png

...but the codebusinessG overrides the last group in groupList instead of being added after it.

Expected behavior

When adding an ej, the ej.codebusinessG + ej.namebusinessG should be added after the last item in groupList.

For context, I am using Angular 5 and the Primeng autocomplete component:

 <p-autoComplete [(ngModel)]="text" [suggestions]="results" (completeMethod)="search($event)"
 emptyMessage={{noBorrowerResult}} 
 [minLength]="3"

 placeholder="Example: Apple"
 [size] = "40"
 field = "name"
 [multiple]="true"
 >
 <ng-template let-elm pTemplate="item">
    <div class="suggestion-item">{{elm.name}} ( ID: {{elm.code}} )</div>
 </ng-template>
 </p-autoComplete>

Answer №1

I've revamped your code and included a sample with this stackblitz.

addToUniqueObjectArray(obj, array, key, altKey?) {
  if (array.some(item => item[key] === obj[altKey ? altKey : key])) { return; }
  array.push(obj);
}

ngOnInit() {
  this.addToUniqueObjectArray(this.newGroup, this.groupList, 'code');
  this.addToUniqueObjectArray(this.newGroup, this.groupList, 'code');

  this.addToUniqueObjectArray(this.ej, this.ejList, 'code');
  this.addToUniqueObjectArray(this.ej, this.ejList, 'code');
  this.addToUniqueObjectArray(this.ej, this.groupList, 'code', 'codebusinessG');
  this.addToUniqueObjectArray(this.ej, this.groupList, 'code', 'codebusinessG');

  console.log('Groups : ', this.groupList, ' EJs : ', this.ejList);

}

You now have a function that compares two keys and only adds to the array if not already present.

If you provide one key, it will use that for comparison, but if you supply an additional key, it changes the comparison method. Test it out on stackblitz to see it in action.

EDIT To prevent reference issues:

this.addToUniqueObjectArray({code: 'CODE'}, this.ejList, 'code');
const newObj = {code: 'CODE'};
this.addToUniqueObjectArray(newObj, this.ejList, 'code');

Pass a new object to the function instead of using one that's already been created.

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

Access to Angular component generation was denied due to EACCES permissions issue

Every time I attempt to create a new component for my Angular application, I immediately encounter a permission denied error without any clear explanation. The command that triggers this issue is ng g component heroes I have attempted to apply chmod -R 7 ...

Exploring the functionality of surveyjs in conjunction with react and typescript

Does anyone have any code samples showcasing how to integrate Surveyjs with React and TypeScript? I attempted to import it into my project and utilized the code provided in this resource. https://stackblitz.com/edit/surveyjs-react-stackoverflow45544026 H ...

Is it possible for a property to be null or undefined on class instances?

Consider this TypeScript interface: export interface Person { phone?: number; name?: string; } Does having the question mark next to properties in the interface mean that the name property in instances of classes implementing the interface ca ...

Organizing a mat-table by date does not properly arrange the rows

My API retrieves a list of records for me. I would like to display these records sorted by date, with the latest record appearing at the top. However, the TypeScript code I have written does not seem to be ordering my rows correctly. Can anyone assist me ...

Utilizing ngx-logger Dependency in Angular 6 for Efficient Unit Testing

Have you ever attempted to test classes in Angular that rely on ngx-logger as a dependency? I am looking for guidance or examples of how this can be achieved using testing frameworks such as Jasmine. It seems there are limited resources available on mock ...

Executing JavaScript functions externally from the Angular 6 application

I have a unique scenario where my angular 6 app is embedded within another application that injects JavaScript to the browser to expose specific functionalities to the angular app. For example, when running my angular app within this external application, ...

Validation of form groups in Angular 2 using template-driven approach

I am seeking guidance on how to handle form validation in Angular 2 template-driven forms. I have set up a form and I want to display a warning if any input within a group is invalid. For example, consider the following form structure: <form class="fo ...

Exploring the process of manually establishing a route change stream in Angular versus utilizing the features of the @angular/router module

Why would a developer choose to manually create a stream of route changes instead of utilizing Angular's ActivatedRoute as recommended in the Angular guide? export class HeroListComponent implements OnInit { heroes$: Observable<Hero[]>; pr ...

Guide to incorporating code coverage in React/NextJs using Typescript (create-next-app) and cypress

I initiated a fresh project using create-next-app with the default settings. npx <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="365544535742531b58534e421b57464676070518021801">[email protected]</a> --- Would you l ...

Elements are receiving CSS properties from other elements within the same component

I'm encountering an issue with my components: 1. I cannot seem to style html and body in signin.component.css for some reason. The workaround I found was using: encapsulation: ViewEncapsulation.None ==> This works perfectly However, when I switch ...

What is the reason behind TypeScript treating numbers as strings when adding them together?

Although TypeScript is strongly typed, can you explain why the code below outputs 12 instead of 3? function add_numbers(a: number, b: number){ return a + b; } var a = '1'; var b = 2; var result = add_numbers(<number><any>a, b) ...

Insert information into a 3-tiered nested Angular FormArray within interconnected dropdown fields

After trying to retrieve data from an API call to populate a select form field, I encountered difficulties setting the value correctly using a FormArray. This led me to creating a FormArray with 3 nested levels in Angular, taking reference from this examp ...

Redirect the user to the shop page in Angular 2 if they already have

How can I set up a redirect for the User ID (this.authTokenService.currentUserData.id) if they are the owner of a shop? owner_id: number; private sub: any; ngOnInit() { this.sub = this.httpService.getShops().subscribe(params => { ...

Stop Angular (click) binding from occurring when the variable is considered 'undefined'

Currently, I am enhancing a custom Angular component by adding callbacks using the standard Angular method, like so: (click)="data.callback ? data.callback() : undefined" This approach works smoothly; when no callback is specified, Angular handl ...

In Angular, encountering difficulty accessing object members within an array when using custom pipes

Here is a custom pipe that I have created, but I am facing an issue accessing the members of the customfilter array, which is of type Item. import { Pipe, PipeTransform } from '@angular/core'; import {Bus} from '/home/pavan/Desktop/Pavan ...

How can I combine my two ngIf conditions into an ngIf else statement?

Having trouble incorporating an *ngIf else with two large <div> elements, as the content seems overwhelming to organize properly while following the documentation. Initially believed that using the same styling for two open text boxes, with one hidd ...

Encountered an issue with Angular Material sidenav: The synthetic listener @transform.start was found

Click here to visit the StackBlitz link Encountering an issue while attempting to utilize the material side nav. Error message: preview-29b0f46fcc27b310236ab.js:1 ERROR Error: Uncaught (in promise): Error: Found the synthetic listener @transform.start. P ...

Issue Encountered with @Input() in TypeScript

I'm currently working on developing an app with Angular 4 and encountered an error message when using @Input('inputProducts') products: Product[]; The specific error I received reads: [tslint] In the class "ProductListComponent", the di ...

Module not found: vueform.config

For my current project, I decided to integrate Vueforms into the codebase. However, when I pasted their installation code into both my .ts and .js files, I encountered errors during the import of vueformconfig and builderconfig. This is a snippet of my ma ...

Can a decorator be added to a Typescript class after it has been created?

Is it possible to update a class with inversify's @injectable decorator after it has been created? My use case involves using a mocking library like ts-auto-mock to generate a mock for me, and then applying the @injectable decorator to bind the mock t ...