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

使用JavaScript处理对象数组,获取各产品最低价

获取每个产品ID对应的最低价报价

给定一组产品报价数据,每个对象对应一个报价,productId可重复但offerId唯一,需求是提取每个productId对应的最低价报价。

现有代码分析

你当前的代码仅完成了按productId分组的操作,还需要进一步筛选每组中的最低价报价。下面是更高效的优化方案,无需先分组再二次遍历,直接通过一次reduce操作完成需求。

优化实现代码

const data = [
    { productId: 'dhdiwu', offerId: 'd3en', price: '$12.20' },
    { productId: 'dhdiwu', offerId: 's2dr', price: '$8.45' },
    { productId: 'dhdiwu', offerId: 'hy38', price: '$21.21' },
    { productId: 'dowksm', offerId: 'ie8u', price: '$1.77' },
    { productId: 'dowksm', offerId: 'djs3', price: '$24.21' },
    { productId: 'dowksm', offerId: 'pies', price: '$92.36' },
    { productId: 'bdbhsu', offerId: '9wid', price: '$100.98' }
];

// 用reduce直接筛选每个产品的最低价报价
const cheapestOffers = data.reduce((result, current) => {
    // 去除价格字符串的$符号,转为数值用于比较
    const currentPrice = parseFloat(current.price.replace('$', ''));
    const productKey = current.productId;

    // 若当前产品无记录,或当前报价比已存最低价更低,则更新
    if (!result[productKey] || parseFloat(result[productKey].price.replace('$', '')) > currentPrice) {
        result[productKey] = current;
    }

    return result;
}, {});

// 将结果转为数组格式(按需选择)
const cheapestOffersArray = Object.values(cheapestOffers);

console.log(cheapestOffersArray);

输出结果

[
  { productId: 'dhdiwu', offerId: 's2dr', price: '$8.45' },
  { productId: 'dowksm', offerId: 'ie8u', price: '$1.77' },
  { productId: 'bdbhsu', offerId: '9wid', price: '$100.98' }
]

方案说明

  • 高效性:仅遍历一次原始数组,避免了分组后二次遍历的额外开销。
  • 逻辑清晰:每次遍历直接对比当前报价与已存储的最低价,实时更新结果。
  • 灵活性:最终结果可保留对象格式(以productId为键)或转为数组格式,按需使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 10:52:07