gpt4 book ai didi

javascript - 我的 reducer 可以使用 Set 作为初始值吗?

转载 作者:行者123 更新时间:2023-11-28 12:13:55 26 4
gpt4 key购买 nike

我正在尝试将对象数组减少为一组唯一值。为此,我尝试使用 Set 作为 reduce() 操作的累加器。

subscriptions = [
{list_id: 'abc', name: 'nom', subscribed: true},
{list_id: 'abc', name: 'nom', subscribed: true},
{list_id: 'ghi', name: 'nom', subscribed: false}];

return subscriptions.reduce((accumulator, currentValue) => {
if (currentValue.subscribed) {
return accumulator.add(currentValue.list_id);
}
}, new Set());

我的测试报告以下错误:

TypeError: Cannot read property 'add' of undefined

我正在尝试做的事情可能吗?我需要通过其他方式做到这一点吗?

最佳答案

如果条件失败,您需要返回累加器。否则默认返回undefined(隐式)。

let subscriptions = [
{list_id: 'abc', name: 'nom', subscribed: true},
{list_id: 'abc', name: 'nom', subscribed: true},
{list_id: 'ghi', name: 'nom', subscribed: false}];

let op = subscriptions.reduce((accumulator, currentValue) => {
if (currentValue.subscribed) {
accumulator.add(currentValue.list_id);
}
return accumulator
}, new Set());

console.log([...op])

关于javascript - 我的 reducer 可以使用 Set 作为初始值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54186493/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com