0

I have an input field wherein users can enter multiple inputs with comma in between.

<div class="container">
    
    Enter your values:<input type="text" multiple #inputCheck>
    <input type="submit"(click)="sendInput(inputCheck.value)">

</div>

These inputs are to be stored in the following array.

 arrayStored=[]

I have tried using the below code but the inputs are not divided in the array and the whole input is seen as a single element inside an array. I need to divide the input into multiple elements and store them inside the array.

     sendInput(event:any){
     this.inputGiven = event;
     this.arrayStored.push(this.inputGiven);

Example: If a user enters SAM,ALEX7,23 and clicks submit , the array should store it as arrayStored=["SAM","ALEX7,"23"] but now it is being stored as arrayStored=["SAM,ALEX7,23"]. How do I split the input and store them as an individual element inside the array ?

6
  • try this.arrayStored = [...this.arrayStored, ...this.inputGiven.split(",")]; Commented Jul 2, 2020 at 11:23
  • It worked but now, if I click submit button again, it replicates the values inside the array. Example: ["SAM","ALEX7,"23","SAM","ALEX7,"23"] I need the values to only appear once even if the submit button is clicked multiple times. Any idea on this please? Commented Jul 2, 2020 at 11:30
  • 1
    try this then. this.inputGiven.split(",").forEach(value => { !this.arrayStored.includes(value) && this.arrayStored.push(value) }); Commented Jul 2, 2020 at 11:34
  • forEach(...) is not iterable (cannnot read propery undefiined) It didn't work. Commented Jul 2, 2020 at 11:44
  • it was untested. anyway you got your answer. Commented Jul 2, 2020 at 11:54

1 Answer 1

2

You can split the elements in an array like so:

 this.arrayStored.concat(this.inputGiven.spilt(“,”));

and to remove any duplicates from the array you can convert it into a set and back into an array like below:

 this.arrayStored = Array.from(new Set(this.arrayStored));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.