Home > Back-end >  I am trying to do input for array that's checking duplicate values
I am trying to do input for array that's checking duplicate values

Time:11-17

Here's what I have : https://stackblitz.com/edit/duplicates-aas5zs?file=app/app.component.ts,app/app.component.html I have little problem. It has to find duplicate values and print them below. Any help ?

I am new in arrays so maybe anyone could help ? I tried google...

CodePudding user response:

Basically you want to write numbers in that input and print out duplicated numbers?

Or you need to know duplicated numbers into an Array?

By the way you don't need to use includes' input because you are already using ngModel, so you already have that value on your logic (.ts file)

CodePudding user response:

I am putting some numbers to input for example: [3, 4, 3, 6, 7]. After click button printing duplicated numbers from this input. I really need help.

CodePudding user response:

There is a problem about that:

You can work on digits from 0 to 9 with this solution, but you will ignore 2-digits numbers, like "10".

By the way, if you just need a duplicated digit finder:

In your .ts, create a new method (or adjust one of yours):

inputNumbersString = '';
  duplicatesResult = [];

      findDuplicates(): void {
        const arrOfDigits = Array.from(String(this.inputNumbersString), Number);
        this.duplicatesResult = arrOfDigits.filter(
          (item, index) => index !== arrOfDigits.indexOf(item)
        );
        console.log(this.duplicatesResult);
      }

From input tag you are getting a string, so you have to convert that string into number and then divide the number into digits, after that you check if there are duplicated number and console.log them. More importantly, you assign the result to variable "duplicatesResult" which you will use into your HTML.

In your HTML:

remove the ng-container and *ngFor which wraps the input, with that you are going to create N-inputs for every array element and you don't need this.

Here your new input and button, now button calls findDuplicates on click, notice that you don't need an input value because you have all the data into the .ts file already:

    <input [(ngModel)]="inputNumbersString" placeholder="Insert numbers please" />
    <button (click)="findDuplicates()">CHECK DUPLICATES</button>
    <span>{{ duplicatesResult }}</span>

The span will order the output.

Now you can re-active the "checked" mechanic if you want, you just have to check duplicatesResult.lenght

  • Related