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

如何在单键值对结构的对象数组中查找最高值与最低值

解决方案

因为你的数组元素都是仅包含单个键值对的对象,我们可以通过Object.values()快速取出每个对象对应的数值,再计算极值,以下是几种常用实现方式:

方法1:提取数值后直接调用Math静态方法

这是最直观的写法,适合小数组场景:

// 提取所有对象的数值为一维数组
const valueList = productArray.map(item => Object.values(item)[0]);
// 计算最高值
const maxValue = Math.max(...valueList); // 输出 5000
// 计算最低值
const minValue = Math.min(...valueList); // 输出 1500

注意:如果数组长度超过JS引擎的函数参数上限(通常为几万级别),扩展运算符会抛出异常,超大数组请使用下面的reduce方法

方法2:单次遍历同时计算最大最小值(性能最优)

用Array.reduce仅遍历一次数组就能得到极值,没有参数长度限制,适合任意大小的数组:

const { max, min } = productArray.reduce((result, currentItem) => {
  const currentValue = Object.values(currentItem)[0];
  return {
    max: currentValue > result.max ? currentValue : result.max,
    min: currentValue < result.min ? currentValue : result.min
  };
}, { max: -Infinity, min: Infinity });
// max 为 5000,min 为 1500

方法3:同时获取极值对应的产品名称

如果需要拿到最高/最低值对应的产品名,可以调整逻辑同时存储键和值:

const { maxItem, minItem } = productArray.reduce((result, currentItem) => {
  const [productName, productValue] = Object.entries(currentItem)[0];
  if (productValue > result.maxItem.value) {
    result.maxItem = { name: productName, value: productValue };
  }
  if (productValue < result.minItem.value) {
    result.minItem = { name: productName, value: productValue };
  }
  return result;
}, { 
  maxItem: { name: '', value: -Infinity }, 
  minItem: { name: '', value: Infinity } 
});
// maxItem 为 { name: 'Product A', value: 5000 }
// minItem 为 { name: 'Product E', value: 1500 }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:39:01