如何链式调用Underscore方法从嵌套数组生成姓名统计对象
问题:修复Underscore链式调用统计NFL球员名字出现次数的代码
原始数据
var nflTeams = [ { name: 'Kansas City Chiefs', playersFirstNames: ['Shane', 'Chad', 'Michael', 'Ronald', 'Blake', 'Noah'], champions: true }, { name: 'Philadelphia Eagles', playersFirstNames: ['Jalen', 'Kenneth', 'Boston', 'Trey', 'Jack', 'Andre', 'Jack', 'Lane', 'Jason', 'Nakobe'], champions: false }, { name: 'Cincinnati Bengals', playersFirstNames: ['Brandon', 'Joe', 'Chris', 'Joe', 'Tyler', 'Trenton', 'Trent', 'Mitchell', 'Alex', 'Trey', 'Ted'], champions: false }, { name: 'San Francisco 49ers', playersFirstNames: ['Jimmy', 'Josh', 'Kyle', 'Jordan', 'Brandon', 'Danny', 'George', 'Tyler', 'Charlie', 'Jake', 'Nick', 'Nick', 'Kevin'], champions: false }, ];
需求
生成统计球员名字出现次数的对象,格式示例:{'Joe':2, 'Jimmy':1, 'Jalen':1 ...},要求通过Underscore的_.chain()链式调用_.map()、_.flatten()、_.reduce()实现,并用三元表达式优化逻辑。
当前错误代码
var firstNameOccurence = { '{players firstName}': 0 }; firstNameOccurence = _.chain (nflTeams) .map(function(team) {return team.playersFirstNames}) .flatten() .reduce(function(newObject, firstName){ console.log ('we have a first name of a player', firstName); return newObject[firstName] = 1 ? !newObject[firstName] : newObject[firstName] += 1; }, {}) .value();
当前代码在_.reduce()阶段失败,最终仅返回布尔值true。
问题原因
- reduce回调返回值错误:reduce的回调函数必须返回累加器对象
newObject,但当前代码返回的是赋值操作的结果(布尔值或数字),导致后续迭代的累加器被替换成这个值,最终结果异常。 - 三元表达式逻辑错误:原表达式的优先级和逻辑完全错误,
newObject[firstName] = 1会先执行赋值,再判断1的真假,实际逻辑完全偏离统计需求。
修复后的代码
var firstNameOccurence = _.chain(nflTeams) .map(team => team.playersFirstNames) .flatten() .reduce((newObject, firstName) => { // 三元表达式判断:名字已存在则计数+1,否则初始化为1 newObject[firstName] = newObject[firstName] ? newObject[firstName] + 1 : 1; // 必须返回累加器对象,保证迭代持续使用同一个对象统计 return newObject; }, {}) .value(); // 输出结果示例:{ Shane:1, Chad:1, Michael:1, ..., Joe:2, Jack:2, ... } console.log(firstNameOccurence);
说明
_.map()提取所有球队的球员名字数组,_.flatten()将二维数组转为一维数组,得到所有球员名字的列表。_.reduce()的回调中,通过三元表达式简洁处理计数逻辑,核心是每次迭代必须返回累加器对象newObject,确保统计结果持续累加到同一个对象中。
内容的提问来源于stack exchange,提问作者curious_orange
相关产品推荐
相关产品推荐

