You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS如何查找对象数组中子女数量最多的联系人?

原代码问题点

  • 直接对比elem_1.children和elem_2.children数组对象,没有取子女数量children.length,数组本身的对比逻辑不符合需求
  • Array.sort()的回调要求返回数值来确定排序顺序,原回调没有返回值,排序逻辑本身无效;且通过排序过程赋值的方式记录最大值,多轮比较会导致结果不可控,不适合用来查找最大值
  • 没有处理空数组、联系人无子女等边界情况

可适配任意长度数组的实现(基于for of循环)

let contacts = [
  {
    name: 'John',
    children:
      [
        { name: 'Mary', age: 11 }
      ]
  }, {
    name: 'Franklin',
    children:
      [
        { name: 'Susy', age: 7 },
        { name: 'Tom', age: 5 }
      ]
  }
];

function p_w_m_children(arr){
  // 空数组直接返回空值
  if (!arr.length) return "";
  let maxChildrenCount = -1;
  let person_w_most_children = "";
  // 遍历所有联系人对比子女数量
  for (const contact of arr) {
    // 兼容无children字段的情况,默认子女数为0
    const currentCount = contact.children?.length || 0;
    if (currentCount > maxChildrenCount) {
      maxChildrenCount = currentCount;
      person_w_most_children = contact.name;
    }
  }
  return person_w_most_children;
}

console.log("The person who has most children is " + p_w_m_children(contacts)+".");
// 输出:The person who has most children is Franklin.

如果需要处理多个人子女数量同为最大值的场景,可以把返回值改成数组,遍历过程中遇到和当前最大值相等的就往数组里加姓名即可。

内容的提问来源于stack exchange,提问作者lp65

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 03:06:04