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

如何在JavaScript中筛选对象数组中指定属性值最大的对象?

获取对象数组中指定属性值最大的对象

首先说明:filter()方法的作用是筛选出所有符合条件的元素,没法直接用来找属性值最大的单个对象,得换思路。下面给你两种实用的实现方式:

方法一:用reduce()(推荐,一步到位)

reduce()可以遍历数组,逐个比较元素的指定属性,最终保留值最大的那个对象。

先给你修正后的示例数组(原代码里的name未定义,这里补全):

const objectArray = [
  { names: "Alice", amount: 3 },
  { names: "Bob", amount: 7 },
  { names: "Charlie", amount: 5 }
];

实现代码:

// 遍历数组,比较每个对象的amount属性,返回值最大的对象
const maxAmountObj = objectArray.reduce((prev, current) => {
  return current.amount > prev.amount ? current : prev;
});

console.log(maxAmountObj); // 输出 { names: "Bob", amount: 7 }

如果担心数组为空导致报错,可以加个初始值判断:

if (objectArray.length === 0) {
  console.log("数组为空,无法获取最大值对象");
} else {
  const maxAmountObj = objectArray.reduce((prev, current) => {
    return current.amount > prev.amount ? current : prev;
  });
  console.log(maxAmountObj);
}

方法二:先找最大值,再筛选对象

如果需要获取所有属性值等于最大值的对象(比如多个对象的amount都是最大),可以用这种方法:

// 第一步:提取所有amount值,用Math.max找到最大值
const maxAmount = Math.max(...objectArray.map(item => item.amount));
// 第二步:筛选出amount等于最大值的所有对象
const maxObjects = objectArray.filter(item => item.amount === maxAmount);

console.log(maxObjects); // 若有多个最大值对象,会返回包含这些对象的数组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 14:20:19