【问题标题】:Return min value from array of objects从对象数组返回最小值
【发布时间】:2021-05-29 01:36:19
【问题描述】:

我有一个对象数组。在每个对象中都有一个包含多个对象的详细信息属性(数组)——在这个例子中我只展示了一个。

我正在寻找每个细节中的 rating 属性并寻找最小值(在本例中为 3.1)...是否有更简单/更清洁的方法来实现这一点?

const ratings = [{ id: 'ABC', details: [{ type: 'VALUE', rating: 9.5 }] }, { id: 'DEF', details: [{ type: 'VALUE', rating: 3.1 }] }, { id: 'GHI', details: [{ type: 'VALUE', rating: 4.5 }] }]
const ids = ['ABC', 'DEF', 'GHI']
const array = []

ids.forEach(element => {
  const valueScore = ratings?.find(r => r.id === element)?.details?.find(c => c.type === 'VALUE')
  if (valueScore.rating) {
    array.push(valueScore.rating)
  }
})
console.log('MIN VALUE', Math.min(...array))

【问题讨论】:

  • 与其遍历 ids 然后使用 find 为什么不只遍历一次 ratings,如果您的代码有效并且您需要反馈/建议,您可能需要查看代码审查SE网站

标签: javascript arrays object ecmascript-6


【解决方案1】:

你可以这样做:

为什么首选这种方法是,您可以在每个评级项以及每个详细信息数组项上完美地运行循环。

  ratings = [
    { id: "ABC", details: [{ type: "VALUE", rating: 9.5 }] },
    {
      id: "DEF",
      details: [{ type: "VALUE", rating: 3.1 }, { type: "VALUE1", rating: 2.1 }]
    },
    { id: "GHI", details: [{ type: "VALUE", rating: 4.5 }] }
  ];

  ids = ["ABC", "DEF", "GHI"];
    const detailsRatingArr = [];
    if (ratings.length === ids.length) {
      ratings.forEach(eachRating => {
        ids.forEach(eachId => {
          if (eachRating.id === eachId) {
            eachRating.details.forEach(eachDetail => {
              detailsRatingArr.push(eachDetail.rating);
            });
          }
        });
      });
    }
    console.log("DETAILS ARRAY ==>", detailsRatingArr);
    detailsRatingArr.sort((a, b) => a - b);
    console.log("Minimum Rating ==>", detailsRatingArr[0]);
  

【讨论】:

    【解决方案2】:

    您可以使用flatMap 然后应用 math.min 来获取最小值:

    const ratings = [{ id: 'ABC', details: [{ type: 'VALUE', rating: 9.5 }] }, { id: 'DEF', details: [{ type: 'VALUE', rating: 3.1 },{ type: 'VALUE1', rating: 2.1 }] }, { id: 'GHI', details: [{ type: 'VALUE', rating: 4.5 }] }];
    
    const ids = ['ABC', 'DEF', 'GHI']
    
    console.log(Math.min(...ratings.flatMap(o=>
        ids.includes(o.id) ? o.details.flatMap(p=>
            p.type=='VALUE' ? p.rating : []) : [])));

    【讨论】:

    • 我正在寻找 VALUE 类型的评级。可能会有另一种类型(例如 { type: 'TEST', rating: 4 } ...我不想看那个
    • 谢谢!此外,我们需要检查最低评分是否是在 ids 数组中找到的 id ...如果评分中有另一个条目,例如 XYZ,则不应包含此条目。可以修改吗?
    • @Michael 那是在 flatMap 中的一个简单检查。已更新。
    • 非常感谢 :) 简单而干净。我总是忘记 flatMap
    猜你喜欢
    • 2021-10-19
    • 2018-02-10
    • 2013-09-28
    • 1970-01-01
    • 2017-07-23
    • 2020-08-06
    • 2021-04-09
    • 1970-01-01
    • 2012-10-26
    相关资源
    最近更新 更多