You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中数组映射、过滤并获取唯一元素的正确方法及语法纠错

Fixing "Illegal return statement" and Extracting Unique Level Values

First, let's break down why your code snippets were causing issues:

  1. Second & Third Snippets: After using map(p => p.Level), you're left with an array of strings (e.g., ["a", "b", "b"]). Trying to access p.Level or p.level on these strings is invalid—strings don't have a Level property! That's why you were seeing errors here.
  2. First Snippet: This one is syntactically valid, but it doesn't handle deduplication. You'd get repeated entries of the same Level value instead of unique ones.

Now, let's implement the correct solution based on your goal: extracting unique Level values (either all unique values from the dataset, or only those matching this.usrInfo.a).

Option 1: Get All Unique Level Values (Sorted)

If you want every distinct Level from the data, sorted alphabetically:

this.myService.myMethod().subscribe(
  data => {
    // Extract all Level values first
    const allLevels = data.map(item => item.Level);
    // Use a Set to deduplicate, then convert back to array and sort
    this.levelsList = [...new Set(allLevels)].sort();
  }
);

Option 2: Get Unique Level Values Matching this.usrInfo.a

If you only want the Level value that matches this.usrInfo.a (ensuring it's added only once, even if it appears multiple times):

this.myService.myMethod().subscribe(
  data => {
    // Filter items where Level matches usrInfo.a, extract the Level value
    const matchingLevels = data
      .filter(item => item.Level === this.usrInfo.a)
      .map(item => item.Level);
    // Deduplicate and sort (though this will only have one unique value if matches exist)
    this.levelsList = [...new Set(matchingLevels)].sort();
    
    // Alternative (simpler for single-value case):
    // this.levelsList = data.some(item => item.Level === this.usrInfo.a) ? [this.usrInfo.a] : [];
  }
);

Key Notes:

  • Set for Deduplication: Using new Set() automatically removes duplicate values from an array—this is the most concise and efficient way to handle uniqueness in modern JavaScript/TypeScript.
  • Arrow Function Syntax: When using arrow functions without curly braces (=>), the return is implicit. If you use curly braces, you need an explicit return (which you had correctly in your first snippet).
  • Avoiding Property Errors: Always check what type of data you're working with after map—if you convert objects to strings, don't try to access object properties on those strings!

内容的提问来源于stack exchange,提问作者haydnD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:21:03