.map() 删除重复项但我想保留重复项?

.map() removes duplicates but I want to keep duplicates?

我有一大堆 API 数据,我过滤成较小的数量。问题是我制作的当前系统使用 .map() 为该数据设置顺序首选项,但它删除了所有重复项。数据按体育联盟过滤,因此如果来自同一联盟的两场比赛进行,两场应该进入最终数组,但只有一场通过。有序数组去除重复项。

const json = (await res.json())?.response;

const ordered = desiredOrder.map((id) => json.find(({ league }) => league?.id === id));

const filtered = [...new Set(ordered)].filter(item => item !== undefined)

这里是 desiredOrdered 数组,每个联赛指定一个数字,然后联赛从最好到最差排名。

var desiredOrder = [
    1, 2, 3, 4, 5, 6, 7, 9, 10, 29, 30, 31, 32, 33, 34, 39, 45, 48, 140, 142, 135, 137, 78, 81, 61, 65, 66, 88, 94, 96, 253, 203, 262, 179, 185,
    144, 188, 169, 40, 41, 42, 43, 235, 207, 218, 141, 136, 333, 307, 197, 62, 79, 80, 128, 130, 292, 98, 101, 103, 106, 113, 119, 283, 71, 73,
    265, 239, 211, 89,
];

这是 API 输出,因此您可以看到 id 的来源(这些元素有 100 多个,这是条目 0)

0:
fixture: {id: 710877, referee: 'Anthony Taylor, England', timezone: 'UTC', date: '2022-05-19T18:45:00+00:00', timestamp: 1652985900, …}
goals: {home: 3, away: 2}
league: {id: 39, name: 'Premier League', country: 'England', logo: 'https://media.api-sports.io/football/leagues/39.png', flag: 'https://media.api-sports.io/flags/gb.svg', …}
score: {halftime: {…}, fulltime: {…}, extratime: {…}, penalty: {…}}
teams: {home: {…}, away: {…}}
[[Prototype]]: Object

因此,使用上面的输出,我需要将另一个 ID 为 39 的游戏过滤到数组中。我已经尝试了很多方法来让它工作,但它不起作用。

如果你想玩 WebDev --> https://footballify.net/test

Github - https://github.com/Footballify/Footballify.github.io/tree/main/test

=nn

map 不会删除重复项,Set 会。

MDN:

Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection.

如果要允许重复,请不要使用 Set


还有MDN

The find() method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

如果要匹配所有结果,请改用 filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

您可能想要 flatten 您分配给 ordered

的数组