如何使用JavaScript统计Phone模式提醒的总数量?
如何用JavaScript统计教练提醒中模式为Phone的总数量?
原始数据
const coachData = [ { "coachName": "Angela", "coachId": 94253, "reminders": [ { "day": "Tuesday", "mode": "Text" }, { "day": "Tuesday", "mode": "Phone" }, { "day": "Tuesday", "mode": "Text" }, { "day": "Tuesday", "mode": "Text" }, { "day": "Tuesday", "mode": "Text" }, { "day": "Tuesday", "mode": "Phone" }, { "day": "Wednesday", "mode": "Text" }, { "day": "Wednesday", "mode": "Text" }, { "day": "Wednesday", "mode": "Text" }, { "day": "Wednesday", "mode": "Text" }, { "day": "Wednesday", "mode": "Text" } ] }, { "coachName": "Melanie", "coachId": 94254, "reminders": [ { "day": "Wednesday", "mode": "Phone" }, { "day": "Wednesday", "mode": "Text" }, { "day": "Wednesday", "mode": "Phone" }, { "day": "Monday", "mode": "Text" }, { "day": "Monday", "mode": "Phone" }, { "day": "Monday", "mode": "Text" }, { "day": "Monday", "mode": "Text" }, { "day": "Monday", "mode": "Text" }, { "day": "Monday", "mode": "Phone" }, { "day": "Monday", "mode": "Text" } ] } ];
解法一:forEach循环累加
初始化计数器,逐层遍历教练列表和对应提醒,判断模式为Phone时累加计数:
let phoneCount = 0; coachData.forEach(coach => { coach.reminders.forEach(reminder => { if (reminder.mode === 'Phone') { phoneCount++; } }); }); console.log(phoneCount); // 输出:6
解法二:reduce链式调用
先用reduce合并所有教练的提醒数组,再通过reduce统计符合条件的数量,写法更简洁:
const phoneCount = coachData .reduce((acc, coach) => acc.concat(coach.reminders), []) .reduce((count, reminder) => { return reminder.mode === 'Phone' ? count + 1 : count; }, 0); console.log(phoneCount); // 输出:6
解法三:flatMap + filter 组合
用flatMap提取所有提醒项,再筛选出模式为Phone的条目,最终取数组长度得到总数:
const phoneCount = coachData .flatMap(coach => coach.reminders) .filter(reminder => reminder.mode === 'Phone').length; console.log(phoneCount); // 输出:6
内容的提问来源于stack exchange,提问作者Saranya
相关产品推荐
相关产品推荐

