Add integer to an array of strings

Currently, I am utilizing an autocomplete feature and aiming to save the IDs of the selected users.

My goal is to store these IDs in a string array, ensuring that all values are unique with no duplicates.

I have attempted to push and convert the values using toString(), but unfortunately, it did not work as expected.

If anyone could provide some assistance, it would be greatly appreciated.

The desired output should look something like this: ["1", "2", "3", "4"]

Check out my code for a working demonstration here.

COMPONENT

 ngOnInit() {
    this.userService.getUsers().subscribe(
      (val: any[]) =>{
        this.allFruits = val.map(user => {
      this.nameIdMap.set(user.username, user.id);
      return user.username
    });
        this.fruitCtrl.setValue(null); //use this to apply changes instantly
      } 
    )
  }

  remove(fruit: string): void {
    const index = this.fruits.indexOf(fruit);

    if (index >= 0) {
      this.fruits.splice(index, 1);
    }
  }

arr:any;
selected(event: MatAutocompleteSelectedEvent): void {
  var a = this.nameIdMap.get(event.option.viewValue);
  console.log(a);
  // var b = this.arr.push(a);
  // var c = b.map((input) => input).join(",").toString();
  // console.log(c)
  this.fruits.push(event.option.viewValue);
  this.fruitInput.nativeElement.value = '';
  this.fruitCtrl.setValue(null);
}

Answer №1

It looks something like this.

selectedItem(event: MatAutocompleteSelectedEvent): void {
  var selectedId = this.nameIdMap.get(event.option.viewValue);
  
  if( this.arr.filter(item => String(selectedId) == item).length < 1) {
      this.arr.push(String(selectedId));
      this.fruits.push(event.option.viewValue);
  }
  console.log(selectedId, this.arr);

  this.inputElement.nativeElement.value = '';
  this.control.setValue(null);
}

Make sure to initialize the arr variable when declaring it.

arr:any[] = [];

I hope this is helpful for you. D;

Answer №2

First things first, your array needs to be initialized before use. To make it a string array, declare it like this:

arr: string[] = [];

Next step is to convert your numbers to strings if you plan on pushing them into the array. Remember that the push method doesn't return the array itself, so adjust your code accordingly by referencing the field directly.

this.arr.push(a.toString());
var c = this.arr.map((input) => input).join(",").toString();
console.log(c)

Answer №3

const set = new Set();
set.add(String(1));
console.log(Array.from(set)); // ["1"]

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

Prevent the SnackBar from extending to full width in case of a smaller window size

Is there a solution to prevent the SnackBar from spanning the entire width of the screen when the window is narrow? ...

Changing the data request body in datatables ajax on button click

My goal is to initially fetch data when the page loads and then allow users to apply filters by clicking on them to fetch updated data. The query I am using is a POST request because it requires complex parameters that need to be formatted as JSON for bett ...

Article: Offering CoffeeScript and JavaScript Assets Simultaneously

Currently, my web app is up and running using Node and Express. I initially developed it in JavaScript but now want to transition over to CoffeeScript. My goal is to have both file1.js and file2.coffee coexisting in the application (with both being served ...

Ways to apply the strategy pattern in Vue component implementation

Here's the scenario: I possess a Cat, Dog, and Horse, all of which abide by the Animal interface. Compact components exist for each one - DogComponent, CatComponent, and HorseComponent. Query: How can I develop an AnimalComponent that is capable of ...

What is the process of sending an HTTP/HTTPS request from a Node.js server?

Currently diving into the world of Node.js, I am experimenting with using a Node.js Application on cPanel to generate a JSON response upon accessing its URL. Upon visiting the app's URL, it seems that the Node.js server is functioning correctly. Afte ...

Having trouble releasing the package on npm platform

I'm facing difficulties in publishing a public package to npm. Despite creating an organization, I'm unable to figure out how to add a new package. Any assistance on this matter would be greatly appreciated. ...

Angular 6: Inconsistent performance of [(ngModel)] functionality

In my Angular 6 project, I am utilizing Bootstrap Modals to implement a specific functionality. Upon clicking the modify button, a modal window should appear with pre-filled values. Although I am using template-driven forms along with [(ngModel)], I have ...

What methods do you use to gather user inputs and transmit them to a server?

I've been struggling to find information online about how to capture user input and submit the data through a POST request to a server, even though this may have already been answered. Currently, I am working with Material UI, React, and JavaScript t ...

Dealing with 'TypeError X is Not a Function' Error in Angular (TypeScript): Occurrences in Certain Scenarios and Absence in Others

Recently, I came across an odd issue in Angular 14 where a type error kept popping up. Although I managed to refactor the code and find a workaround, I'm quite intrigued as to why this issue is happening so that I can prevent it from occurring again i ...

Traversing Abstract Syntax Trees Recursively using TypeScript

Currently in the process of developing a parser that generates an AST and then traversing it through different passes. The simplified AST structure is as follows: type LiteralExpr = { readonly kind: 'literal', readonly value: number, }; type ...

Querying a map within a Mongo function results in an empty variable when accessed outside of the function, but

Currently, I am facing an issue while trying to create an array of objects using the map function in Mongo and node/express JS. Strangely, when I utilize console.log outside the map function, the array appears empty. However, within the map function, each ...

Sorting a function with two parameters in descending order is possible even when dealing with an empty array and no initial value for reduction

My npm test is not passing the third out of six tests. I have attempted to sort it using the following code snippet: sumAll.sort(function(min,max)) { return max - min; } However, this approach did not work. I also tried incorporating conditionals in t ...

The error message "Uncaught ReferenceError: e is not defined" is popping up in my code when

As a beginner with React and Material-UI, I am encountering an error that I cannot seem to resolve. When I load a component using material-ui/data-grid, the data grid simply displays "An error occurred" in the app. However, when I load the component withou ...

finding the adjacent li element using the document.(property)

Utilizing a pub/sub solution named ably.io for real-time data updates, I have implemented a method that assigns dynamic ids to each ngFor listing. This allows me to easily identify and update the values received from ably.io subscribe. document.getElement ...

Maintaining active navigation state in JQuery/JavaScript after clicking a link: tips and tricks

While many resources discuss adding the active class to a nav link using jquery, there is less information on maintaining the active state after the nav link has been clicked. After experimenting with code from various sources, I have attempted to set ses ...

Leverage the router through the getServerSideProps method

My goal is to automatically redirect the user to the login page if their token has expired. I need to handle this in the getServerSideProps method where I make a request to the server for data. If the request is unauthorized, I want to use the useRouter ho ...

How to eliminate duplicate items in an array and organize them in JavaScript

I am looking to eliminate any duplicate items within an array and organize them based on their frequency of occurrence, from most to least. ["57358e5dbd2f8b960aecfa8c", "573163a52abda310151e5791", "573163a52abda310151e5791", "573163a52abda310151e5791", "5 ...

typescript throwing an unexpected import/export token error

I'm currently exploring TypeScript for the first time and I find myself puzzled by the import/export mechanisms that differ from what I'm used to with ES6. Here is an interface I'm attempting to export in a file named transformedRowInterfac ...

Master the art of using Insertion Sort in javascript with the help of Khan Academy

Seems like I am almost there with solving this problem, but my code isn't running as expected. Can someone offer some feedback and point out where I went wrong? var insert = function(array, rightIndex, value) { for(var j = rightIndex; j & ...

The ng lint command is successful, yet an error appears in VS Code

I'm currently utilizing the tslint tool in my Angular project. Here is an excerpt from my tsconfig.json file: { "compileOnSave": false, "compilerOptions": { "downlevelIteration": true, "impor ...