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

如何在JavaScript命名数组中查找最小值?求新实现方案

在对象数组中查找最低价格的现代方法

嘿,这个问题问得很到位!你说得没错,多年前的方案确实可能不够简洁高效,现在用现代JavaScript语法能更优雅地解决这个问题。针对你给出的这个每个元素包含独特价格属性和名称的对象数组,我给你整理几种实用的方法:

方法1:结合map()和Math.min()

先把每个对象里的价格提取成纯数值数组,再用Math.min()快速获取最小值。因为你的价格属性键名不统一(brandy/whiskey/vodka),所以需要用Object.values()配合过滤来精准提取价格:

let drink_prices = [ 
  {brandy:25, name: "brandy drink"}, 
  {whiskey:20, name: "whiskey drink"}, 
  {vodka:46, name: "vodka drink"} 
];

// 提取所有价格到数组
const priceArray = drink_prices.map(item => 
  Object.values(item).find(val => typeof val === 'number')
);

// 展开数组传入Math.min()获取最小值
const lowestPrice = Math.min(...priceArray);
console.log(lowestPrice); // 输出20

小提示:如果数组可能为空,记得先做判断,避免Math.min()返回Infinity的问题。

方法2:使用Array.reduce()(更高效)

reduce()可以直接在遍历过程中完成价格比较,不需要额外生成价格数组,性能更优,尤其适合处理大型数组:

let drink_prices = [ 
  {brandy:25, name: "brandy drink"}, 
  {whiskey:20, name: "whiskey drink"}, 
  {vodka:46, name: "vodka drink"} 
];

const lowestPrice = drink_prices.reduce((minPrice, currentItem) => {
  const currentPrice = Object.values(currentItem).find(val => typeof val === 'number');
  return currentPrice < minPrice ? currentPrice : minPrice;
}, Infinity); // 初始值设为Infinity,确保第一个价格能替换它

console.log(lowestPrice); // 输出20

如果还想同时拿到最便宜的饮品完整信息,稍微修改逻辑就行:

const cheapestDrink = drink_prices.reduce((cheapest, current) => {
  const currentPrice = Object.values(current).find(val => typeof val === 'number');
  const cheapestPrice = Object.values(cheapest).find(val => typeof val === 'number');
  return currentPrice < cheapestPrice ? current : cheapest;
}, drink_prices[0]);

console.log(cheapestDrink); // 输出{whiskey:20, name: "whiskey drink"}

关于传统for循环

你考虑的for循环当然也能实现,兼容性拉满,但写法相对繁琐:

let drink_prices = [ 
  {brandy:25, name: "brandy drink"}, 
  {whiskey:20, name: "whiskey drink"}, 
  {vodka:46, name: "vodka drink"} 
];

let lowestPrice = Infinity;
for (let i = 0; i < drink_prices.length; i++) {
  const currentPrice = Object.values(drink_prices[i]).find(val => typeof val === 'number');
  if (currentPrice < lowestPrice) {
    lowestPrice = currentPrice;
  }
}

console.log(lowestPrice); // 输出20

关键注意点

  • 因为你的价格属性键名不统一,必须用Object.values()或Object.entries()提取价格,不能直接用固定键名访问;
  • 如果后续数组结构变化(比如出现多个数值属性),要调整提取逻辑,确保拿到正确的价格值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:17:49