查找包含最多元素的对象



我编写了一个函数,它将返回联系人列表(对象数组)中具有最多子元素的名称,但它受限于我在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)+ ".");

使用arr查找拥有最多孩子的人。排序时,可以使用以下命令:

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为正,elem_1.children.length < elem_2.children.length为负,相等时为0。这意味着排序函数可以对数组进行正确排序。

然后,一旦数组被排序,您可以简单地获得排序数组中的最后一个元素(值最大的元素)。

编辑澄清

let sortedArr = arr.sort((elem_1, elem_2) => {
return elem_1.children.length - elem_2.children.length;
};
return sortedArr[sortedArr.length - 1].name;

您可以遍历数组并保留拥有最多孩子的联系人的记录。如果子节点数目大于,则将该记录替换为循环中的当前记录。

然后在循环结束时返回该触点。

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',
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;
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 + ".");

最新更新