简体   繁体   English

需要帮助来理解在数组上使用 reduce() 的 react-native 代码

[英]Need help to understand a react-native code that uses reduce() on an array

This code is from a simple React Native Contacts app, it's supposed to use reduce method to:这段代码来自一个简单的 React Native Contacts 应用程序,它应该使用reduce方法来:

for each contact in the array contacts , extract and uppercase the first letter, then return an object that maintains all the previous keys of object and appends this current contact to the key which matches it's first letter.对于数组contacts中的每个联系人,提取第一个字母并将其大写,然后return一个 object,它维护 object 的所有先前键并将此当前联系人附加到与其第一个字母匹配的键。

//contacts is an array of objects {key, name, phone} //contacts 是一个对象数组 {key, name, phone}

  const contactsByLetter = props.contacts.reduce((obj, contact) => {
    const firstLetter = contact.name[0].toUpperCase()
    return {
      ...obj,
      [firstLetter]: [...(obj[firstLetter] || []), contact],
    }
  }, {})

reduce syntax is arr.reduce(callback( accumulator, currentValue[, index[, array]] )[, initialValue]) First, I don't see where the obj argument is in the syntax. reduce 语法是arr.reduce(callback( accumulator, currentValue[, index[, array]] )[, initialValue])首先,我看不到obj参数在语法中的位置。 Second, I understand how spread notation work but I don't get the whole return part specially [...(obj[firstLetter]其次,我了解扩展符号的工作原理,但我没有特别得到整个返回部分[...(obj[firstLetter]

The code is in this file SectionListContacts file , the entire code here代码在这个文件SectionListContacts 文件中,整个代码在这里

Appends this current contact to the key which matches it's first letter:将此当前联系人附加到与其首字母匹配的键上:

  [firstLetter]: [...(obj[firstLetter] || []), contact],

For example,例如,

{a: ['user a1', 'user a2'] }

so,所以,

[a]: [...(['user a1', 'user a2'] || []), 'user a3']

then,然后,

[a]: ['user a1', 'user a2', 'user a3']

[ EDITED ] [已编辑]

obj is the previous value. obj是前一个值。 The first value of it is the initial value set like它的第一个值是设置的初始值,如

const initialValue = 10;
[1,2,3].reduce((prev, current) => prev + current, initialValue)
// 10 + (1+2+3) = 16

In your case, obj initial value is {} .在您的情况下, obj初始值为{}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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