![](/img/trans.png)
[英]What are the advantages of Javascript's reduce() function? (and map())
[英]Advantages of using JavaScript reduce compared to map function
当然,有很多问题可以比较 JavaScript 的reduce
函数和map
函数。 但是我的问题与我的问题完全相关,我应该根据条件更改集合中的项目,我可以用两种方式编写,使用map
或使用reduce
:
// using map function
const formGroupModifierToMultiSelectLocation = (groups: Object[]) =>
groups.map(({ components: cs, ...other }) => ({
components: cs.map(({ type, ...rest }) => ({
multiple: type === 'location',
type,
...rest,
})),
...other,
}));
// using reduce function
const formGroupModifierToMultiSelectLocation = (groups: Object[]) =>
groups.reduce(
(acc, { components: cs, ...other }) => [
...acc,
{
components: cs.map(({ type, ...rest }) => ({
multiple: type === 'location',
type,
...rest,
})),
...other,
},
],
我更喜欢使用map
因为它比reduce
更具可读性。 我不知道,也许就我而言,使用reduce
有一些我不知道的优势。 在代码审查中,审查者建议我使用reduce
而不是map
。 我没有理由更改我的代码。
实际问题:在我的情况下,与 map 函数相比,使用 JavaScript reduce 的优势是什么?
如果要将数组转换为对象, reduce
会很有帮助。 如果您只想修改一个数组,那么map
就可以正常工作。
例如,考虑要删除某个键的数据对象。
const data = {
a: 'x',
b: 'y',
c: 'z',
}
Object.keys(data).filter((item) => item !== 'b').reduce((carry, item) => ({
...carry,
[item]: data[item],
}), {})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.