简体   繁体   中英

Advantages of using JavaScript reduce compared to map function

Surely, there are plenty of questions to compare JavaScript reduce function to map function. But my question is exactly related to my issue, I should change an item inside a collection based on a condition, I can write in two ways, using map or using 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,
      },
    ],

I prefer to use map because it is more readable than reduce . I don't know, maybe in my case using reduce has some advantages that I don't know them. In code-review, the reviewer proffers me to use reduce instead of map . I have no reason to change my codes.

Actual Question: What are the advantages of using JavaScript reduce compared to map function in my case?

reduce is helpful if you want to convert an array into an object. If you just want to modify an array, then map will work just fine.

As an example, consider an object of data where you want to remove a certain key.

const data = {
    a: 'x',
    b: 'y',
    c: 'z',
}

Object.keys(data).filter((item) => item !== 'b').reduce((carry, item) => ({
    ...carry,
    [item]: data[item],
}), {})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM