如何统计指定用户的好友中姓名以指定字母开头的人数
统计指定用户好友中姓名以指定字母开头的人数
给定一个由用户对象组成的数组,每个用户对象包含friends数组,数组内的好友对象都有name属性。需要实现一个函数,统计指定用户的好友里姓名以指定字母开头的人数。
原始数据与初始实现代码
var customers = [{ name: "Courtney", age: 43, balance: "$3,400", friends: [{ id: 0, name: "Justice Lara" }, { id: 1, name: "Duke Patrick" }, { id: 2, name: "Herring Hull" }, { id: 3, name: "Johnnie Berg" }] }, { name: "Regina", age: 53, balance: "$4,000", friends: [{ id: 0, name: "Cheryl Kent" }, { id: 1, name: "Greta Wells" }, { id: 2, name: "Gutierrez Waters" }, { id: 3, name: "Cooley Jimenez" }] }, { name: "Jay", age: 28, balance: "$3,000", friends: [{ id: 0, name: "Cross Barnett" }, { id: 1, name: "Raquel Haney" }, { id: 2, name: "Cassandra Martin" }, { id: 3, name: "Shelly Walton" }] }]; var friendFirstLetterCount = function(array, customer, letter) { let friendNames = []; for (let i = 0; i < customer.friends.length; i++) { friendNames.push(customer.friends[i].name); } let friendCount = _.filter(friendNames, function(current, index, array) { return current.toLowerCase().charAt(0) === letter.toLowerCase(); }); return friendCount.length; };
优化实现方案
简化filter写法(去掉冗余的名字数组)
不需要先提取好友名字到新数组,直接过滤好友对象即可,减少内存占用:
var friendFirstLetterCount = function(array, customer, letter) { const targetLetter = letter.toLowerCase(); return customer.friends.filter(friend => friend.name.toLowerCase().charAt(0) === targetLetter ).length; };
使用reduce实现(符合最初计划)
如果想用reduce来累计数量,可以直接在遍历好友数组时统计符合条件的人数:
var friendFirstLetterCount = function(array, customer, letter) { const targetLetter = letter.toLowerCase(); return customer.friends.reduce((count, friend) => { return friend.name.toLowerCase().charAt(0) === targetLetter ? count + 1 : count; }, 0); };
完整实用版(加入用户查找逻辑)
原函数参数中的用户数组array未被使用,可增加根据用户名查找用户的逻辑,让函数更实用:
var friendFirstLetterCount = function(customers, customerName, letter) { // 从用户数组中找到目标用户 const customer = customers.find(c => c.name === customerName); // 未找到用户时返回0 if (!customer) return 0; const targetLetter = letter.toLowerCase(); return customer.friends.reduce((count, friend) => { return friend.name.toLowerCase().charAt(0) === targetLetter ? count + 1 : count; }, 0); }; // 使用示例:统计Regina的好友中姓名以G开头的人数 console.log(friendFirstLetterCount(customers, "Regina", "G")); // 输出2
优化说明
- 避免创建冗余的名字数组,直接操作原好友对象,提升效率
- 将目标字母转小写的操作只执行一次,减少重复计算
- 加入用户查找逻辑,让函数可以直接通过用户名定位目标用户,无需外部传入用户对象
- reduce版本直接累计符合条件的数量,更贴合最初的技术计划
内容的提问来源于stack exchange,提问作者GloriousKaboom
相关产品推荐
相关产品推荐

