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

JavaScript中提取对象数组里嵌套对象的唯一值的高效方法

Efficiently Get Unique Person IDs from Request Array

Great question! Your current implementation gets the job done reliably, but we can streamline it into more concise and potentially efficient approaches. Let’s break down a few solid options:

One-Liner with map + Set

This cuts out the manual loop and intermediate array entirely by combining ID extraction and deduplication in one step:

const uniquePeopleIds = Array.from(new Set(requests.map(req => req.person.id)));

Here’s how it works: requests.map() transforms the original array into a list of just person.id values, the Set automatically strips out duplicates, and Array.from() converts the Set back into a standard array. It’s clean, readable, and performs nearly identically to your original approach for most everyday use cases.

Single-Traversal with reduce + Set

If you’re working with extremely large arrays and want to minimize the number of times you iterate through the data (your original approach does two full traversals: one for the loop, one for the Set), this approach only goes through the array once:

const uniquePeopleIds = requests.reduce((acc, req) => {
  const personId = req.person.id;
  if (!acc.set.has(personId)) {
    acc.set.add(personId);
    acc.ids.push(personId);
  }
  return acc;
}, { ids: [], set: new Set() }).ids;

We use a reducer that tracks both the final array of unique IDs and a Set for O(1) fast duplicate checks. This avoids creating a full intermediate array of all IDs first, which can save memory for very large datasets.

Simplified reduce (for smaller arrays)

For smaller arrays, a simpler reducer without a Set is also an option—though note that Array.includes() is an O(n) operation, so this will be slower than the Set-based methods for large datasets:

const uniquePeopleIds = requests.reduce((acc, req) => {
  const personId = req.person.id;
  if (!acc.includes(personId)) acc.push(personId);
  return acc;
}, []);

All these approaches will give you the exact [1, 2, 3] result you need. Your original method is totally valid and easy to follow—these alternatives just offer more concise syntax or minor performance tweaks depending on your specific use case.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 23:04:09