如何使用Array.map函数从数组数组中获取新集合?

发布于 2025-01-19 13:57:23 字数 522 浏览 3 评论 0原文

现在正在探索 Sets,但无法从其中的 x 数组数组中获取新 Sets。 我在 new Set() 中使用 Array.map 方法。

这是我正在尝试做的事情,它看起来很合乎逻辑,但最终只有来自第一个数组的值:

new Set(...array.map(x => x.value));

了解我做错了什么以及它应该如何

更新: 为了更清楚地说明我的需求:

const array = [[1,1,3,4], [2,2,3,4], [1,1,3,5]];
new Set(...array.map(x => x));

我的目标是拥有 [1,2,3,4,5] 但获得 [1,3,4]

解决方案

 new Set(array.map(x => x.value).flat())

Exploring Sets now and could not get a new Set from an array of x arrays in it.
I what to use Array.map method inside new Set().

Here is what I'm trying to do, and it seems logical, but in the end having values only from the 1st array:

new Set(...array.map(x => x.value));

Will be awesome to understand what I am doing wrong and how it should look like

Update:
To be more clear in my need:

const array = [[1,1,3,4], [2,2,3,4], [1,1,3,5]];
new Set(...array.map(x => x));

My goal to have [1,2,3,4,5] but getting [1,3,4]

Solution:

 new Set(array.map(x => x.value).flat())

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

执笏见 2025-01-26 13:57:23

您只需要数组,而不是传播参数:

new Set(array.map(x => x.value));

from <代码> set

语法

  new Set()
新套装(可见)
 

,您首先需要一个公寓:

const
    array = [[1, 1, 3, 4], [2, 2, 3, 4], [1, 1, 3, 5]],
    unique = new Set(array.flat()),
    result = [...unique].sort((a, b) => a - b);

console.log(...unique); // still a set
console.log(...result); // array, sorted

You need only the array, not spreaded parameters:

new Set(array.map(x => x.value));

From Set:

Syntax

new Set()
new Set(iterable)

With a nested array, you need a flat it first:

const
    array = [[1, 1, 3, 4], [2, 2, 3, 4], [1, 1, 3, 5]],
    unique = new Set(array.flat()),
    result = [...unique].sort((a, b) => a - b);

console.log(...unique); // still a set
console.log(...result); // array, sorted

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文