当对象数组为空时,maxby 返回 undefined 或可选择抛出错误;若多个对象属性值相同且最大,则返回第一个遇到的对象;该方法时间复杂度为 o(n),可通过避免重复计算或使用高效遍历方式优化,但需权衡实现复杂性与实际性能需求。

获取 JavaScript 对象数组中的最大值,通常需要指定一个属性作为比较的依据。
maxBy
解决方案:
function maxBy(arr, fn) {
if (!arr || arr.length === 0) {
return undefined; // 或者抛出错误,取决于你的需求
}
if (typeof fn !== 'function') {
throw new Error('fn must be a function');
}
let maxVal = fn(arr[0]);
let maxObj = arr[0];
for (let i = 1; i < arr.length; i++) {
const currentVal = fn(arr[i]);
if (currentVal > maxVal) {
maxVal = currentVal;
maxObj = arr[i];
}
}
return maxObj;
}
// 示例
const objects = [
{ id: 1, value: 10 },
{ id: 2, value: 5 },
{ id: 3, value: 15 },
];
const maxObject = maxBy(objects, (obj) => obj.value);
console.log(maxObject); // 输出: { id: 3, value: 15 }如何处理对象数组为空的情况?
如果对象数组为空,上面的
maxBy
undefined
null
如果比较的属性值相同,
maxBy
当前的
maxBy
maxBy
当前的
maxBy
maxBy
reduce
for
fn
maxBy
以上就是js 如何用maxBy获取对象数组的最大值的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号