What is the best way to utilize mapping and filtering distinct values in an array using TypeScript?

What is the best way to filter and map distinct elements from an array into another array?

I've experimented with various methods but keep encountering a syntax error stating "Illegal return statement".

My objective is to display only unique items from an array, for example, adding 'Level' = 'b' to the 'levelsList' array only once.

// Here is a simplified version of the dataset returned by myService.myMethod() that requires filtering:
[
 {
    "ID": 1,
    "Level": "a",
    "Year": 1
  },
  {
    "ID": 2,
    "Level": "b",
    "Year": 2
  },
  {
    "ID": 3,
    "Level": "b",
    "Year": 2
  },
]


levelsList: string[] = [];

// Syntax error arises at 'level.Level'
         this.myService.myMethod().subscribe(
           data => {
             this.levelsList = data
               .filter((level) => {
                 return level.Level === this.usrInfo.a;
               }).map((level) => {
                 return level.Level;
               }).sort();
           });

 // Another syntax error can be found at p.Level while filtering
         this.myService.myMethod().subscribe(
           data => {
             this.levelsList = data.map(p => p.Level).filter(p => p.Level === this.usrInfo.a).sort();
           });

 // Yet another syntax error occurs in this block
         this.myService.myMethod().subscribe(
           data => {
             this.levelsList = data.map((p) => p.Level)
               .filter((p) => p.level === this.usrInfo.a).sort();
           });

Answer №1

Thanks for following my recommendation


        const selectedLevel = "a";

        this.result = this.json
               .filter((item) => {
                 return item.Level == selectedLevel;
               })
               .map((level) => {
                 return level.Level;
               })
               .filter((value,index,self) => {
                 return self.indexOf(value) == index;
               })
               .sort(); 

For more examples, visit https://codeburst.io/javascript-array-distinct-5edc93501dc4. I also created a plunker to test it out:

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

What direction does Angular2 animation rotate in?

In my Angular2 application, I am trying to create a menu icon that rotates clockwise when shown. The desired animation is for it to rotate from -360 degrees to -180 degrees when displayed and from -180 degrees to 0 degrees when hidden. Currently, the anim ...

When using Webpack, there may be difficulties resolving relative path import of express static files

I am currently developing an Outlook add-in with an Express server running. To ensure compatibility with Outlook Desktop, I need to transpile JavaScript to ES5 using Webpack. Below is the simplified structure of my project: /public /javascripts ssoAu ...

Looking for a demonstration using dust.js or handlebars.js in a two-page format with express3.x and node?

Currently, I am in the process of selecting a templating engine to use. While I have come across numerous single-page examples utilizing template engines, I am specifically searching for a practical example that demonstrates handling two distinct pages whi ...

What causes a user to log out when the page is refreshed in a React/Redux application?

Each time the page is reloaded in my React/Redux application, the user gets logged out, even though I have stored the token in localStorage. There seems to be an error somewhere. The token should ideally be saved when the user logs in and not lost upon rel ...

Transfer a file to Amazon S3 using the Microsoft Office Add-In

I am working on developing a JavaScript Microsoft Office add-in that allows users to save a document to an S3 bucket. However, I have not been able to find a way to achieve this. Has anyone managed to successfully make this work before? ...

Best practices for transferring data in node.js (unresolved)

Is it possible to pipe a file from an external server through localhost using Node.JS? (Imagine loading localhost as if it were another site like ) Here is the scenario: A PC requests http://localhost:80/highres/switch.html The Node application then ...

The Cordova InAppBrowser plugin has not been properly set up

After running cordova plugin list, I noticed that the InAppBrowser plugin is listed. However, when I try to run my code on an android device, I receive this message in the console via Chrome Remote Debugger: Native: InAppBrowser is not installed or you ar ...

Looking to build a unique form validator for two inputs? Ensure that one input number is consistently larger than the other with this guide

Is it possible to create a custom form validator with 2 inputs? My goal is to ensure that one input number is always greater than the other. ValidateMaxMin(control: FormControl) { console.log(control.value.productMin); if (control.value.productM ...

Incorporating JavaScript into a Rails Application

When I click on a link "link_to" in my rails app, I am attempting to trigger a JS file. To confirm that the asset pipeline is functioning correctly, I conducted a test with: $(document).ready(function() { alert("test"); }); The alert successfully po ...

Store the selected checkbox values in an array when submitting in Ionic

One issue I am facing is that the checked checkboxes are returning true instead of the value of input (type="checkbox"). Array displaying responded checked or unchecked items I am unable to store this data in an array as needed. Additionally, I cannot sp ...

Enlarging the modal overlay

My Angular/Bootstrap app features a small text area within a modal window that often contains lengthy content exceeding the size of the textarea and modal itself. I am looking to incorporate a button within the modal window that, when clicked, opens a lar ...

How can I dynamically populate my select field with JSON data using React.js?

My goal is to fetch data from an API and use the 'symbol' JSON field as options for a select dropdown. However, I'm encountering an issue: 'TypeError: Cannot read property 'length' of undefined.' Beneath my code, I' ...

Leveraging symbols as object key type in TypeScript

I am attempting to create an object with a symbol as the key type, following MDN's guidance: A symbol value may be used as an identifier for object properties [...] However, when trying to use it as the key property type: type obj = { [key: s ...

The React SwiperJs autoplay feature seems to be malfunctioning, as the swiper is not automatically

I have been utilizing the Swiper component in React from this link. However, I encountered an issue with setting it to autoplay as it doesn't auto swipe. Here is my attempted code: // Resource: https://swiperjs.com/get-started/ import React from &apos ...

Configuring ordered imports in TSLint

Need help with configuring my TSLint rule ordered-imports. I want the import order to be like this: // React import React from 'react'; import { View } from 'react-native'; // Libs import * as _ from 'lodash'; import * as mo ...

Is it feasible to activate a Bootstrap Tooltip from a different element?

I am currently developing a system that enables users to add notes over an image they upload. Presently, I have a note div that, upon clicking, opens a text box for editing. When hovering over this div, I utilize Bootstrap Tooltip to preview the contents o ...

Creating a visual representation of data using Google Charts to display a stacked bar chart

I wrote a script to display a stacked Google chart using JSON data stored on the wwwroot directory - <html> <head> <title>DevOps Monitoring Application</title> <link rel="icon" type="image/png" hr ...

Update a div in PHP using the data received from an AJAX response

I recently developed a PHP application and encountered an issue with updating the value of a date picker. The user is prompted for confirmation when changing the date, and upon confirmation, the date in the "expiry" field (with id expiry) should update alo ...

How can I retrieve an attribute from another model in Ember using the current handlebar in the HTML file?

I'm attempting to achieve the following: {{#if model.user.isAdmin}} <div> My name is {{model.user.name}} </div> {{/if}} within a handlebar that is being used in a controller unrelated to users: <script type="text/x-handlebars" data- ...

Managing state in React for a nested object while still maintaining the data type of the

Exploring the question further from this particular query Updating State in React for Nested Objects The process of updating nested state involves breaking down the object and reconstructing it as shown below: this.setState({ someProperty: { ...this.stat ...