与 map 函数相比,使用 JavaScript reduce 的优势
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],
}), {})
当然,有很多问题可以比较 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],
}), {})