如何解决查找元素数量最多的对象
我编写了一个函数,该函数将从联系人列表(对象数组)中返回具有最多子项的名称,但它仅限于我在 if 语句中包含的元素数量。无论大小如何,我如何让它遍历此联系人列表中的所有元素?我尝试创建一个 for of 循环,但它不会让我使用计数器“I”对元素进行排序,从而返回错误。
提前致谢!
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){
let person_w_most_children = "";
arr.sort((elem_1,elem_2) => {
if (elem_1.children > elem_2.children){
person_w_most_children = elem_1.name;
}else{
person_w_most_children = elem_2.name;
}
});
return person_w_most_children;
}
console.log("The person who has most children is " + p_w_m_children(contacts)+ ".");
解决方法
您可以遍历数组并记录拥有最多孩子的联系人。如果孩子的数量更多,则将该记录替换为循环中的当前记录。
然后在循环完成后返回该联系人。
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) {
let person_w_most_children;
contacts.forEach(contact => {
if (!person_w_most_children || contact.children.length > person_w_most_children.children.length) {
person_w_most_children = contact;
}
})
return person_w_most_children;
}
console.log("The person who has most children is " + p_w_m_children(contacts).name + ".");
同上,不使用 forEach
:
let contacts = [{
name: 'John',age: 5
}
]
}];
function p_w_m_children(arr) {
let person_w_most_children;
for (let i = 0; i < contacts.length; i++) {
if (!person_w_most_children || contacts[i].children.length > person_w_most_children.children.length) {
person_w_most_children = contacts[i];
}
}
return person_w_most_children;
}
console.log("The person who has most children is " + p_w_m_children(contacts).name + ".");
要使用 arr.sort 查找孩子最多的人,您可以使用以下内容:
RUN apt-get update && \
apt-get install -y --no-install-recommends \
ca-certificates bash-completion tar less \
python-pip python-setuptools build-essential python-dev \
python3-pip python3-wheel && \
rm -rf /var/lib/apt/lists/*
关键点在于您比较数组的 arr.sort((elem_1,elem_2) => {
return elem_1.children.length - elem_2.children.length
}
(而不仅仅是比较数组本身)并且 .length
回调返回一个可以排序的值。 .sort
时返回正数,elem_1.children.length > elem_2.children.length
时返回负数,相等时返回 0。这意味着 sort 函数可以正确地对数组进行排序。
然后,一旦对数组进行排序,您就可以简单地获取已排序数组中的最后一个元素(具有最大值的元素)。
编辑以澄清
elem_1.children.length < elem_2.children.length
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。