javascript - 将数组中对象的最大值显示为两个最大值

标签 javascript arrays reduce

我有一个来自 api 响应及其对象的数组。我需要找到具有最大总计的值并且我已经显示它我无法解决它,当总计有两个最大值时。是否有有什么解决办法吗?

myArray[
{time: "2018-12-02", total: 25, percentage: 20, averageTime: 20},
{time: "2018-13-02", total: 25, percentage: 20, averageTime: 20},
{time: "2018-14-02", total: 35, percentage: 25, averageTime: 25},
{time: "2018-16-02", total: 65, percentage: 60, averageTime: 20},
{time: "2018-17-02", total: 40, percentage: 20, averageTime: 20},
{time: "2018-18-02", total: 65, percentage: 20, averageTime: 20},
{time: "2018-18-02", total: 35, percentage: 23, averageTime: 20}
];

我试过这样的 reduce 函数:

var data =[];
data.reduce((max, p) => p.total > max ? p.total : max, data[0].total);

最佳答案

你可以这样做:

想法:

  • 创建一个以 total 作为键和一个变量来保存最大值的 hashMap。
  • 检查键是否存在,如果不存在,将其初始化为一个数组。
  • 将当前对象压入该数组。
  • 获取以 max 为键的数组,您将获得总计最大的所有值。

现在您已经有了整个对象,您可以迭代并显示任何必要的值。

var myArray = [{time: "2018-12-02", total: 25, percentage: 20, averageTime: 20},
{time: "2018-13-02", total: 25, percentage: 20, averageTime: 20},
{time: "2018-14-02", total: 35, percentage: 25, averageTime: 25},
{time: "2018-16-02", total: 65, percentage: 60, averageTime: 20},
{time: "2018-17-02", total: 40, percentage: 20, averageTime: 20},
{time: "2018-18-02", total: 65, percentage: 20, averageTime: 20},
{time: "2018-18-02", total: 35, percentage: 23, averageTime: 20}]

var max = 0;
var hashMap = myArray.reduce((acc, p) => {
  max = Math.max(max, p.total);
  acc[p.total] = acc[p.total] || [];
  acc[p.total].push(p);
  return acc;
}, {});

console.log(hashMap[max]);

只有时间值(value)

var myArray = [{time: "2018-12-02", total: 25, percentage: 20, averageTime: 20},
{time: "2018-13-02", total: 25, percentage: 20, averageTime: 20},
{time: "2018-14-02", total: 35, percentage: 25, averageTime: 25},
{time: "2018-16-02", total: 65, percentage: 60, averageTime: 20},
{time: "2018-17-02", total: 40, percentage: 20, averageTime: 20},
{time: "2018-18-02", total: 65, percentage: 20, averageTime: 20},
{time: "2018-18-02", total: 35, percentage: 23, averageTime: 20}]

var max = 0;
var hashMap = myArray.reduce((acc, p) => {
  max = Math.max(max, p.total);
  acc[p.total] = acc[p.total] || [];
  acc[p.total].push(p.time);
  return acc;
}, {});

console.log(hashMap[max]);

关于javascript - 将数组中对象的最大值显示为两个最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49271325/

相关文章:

javascript - 如何在单击时使全宽 div 出现在网格项下

javascript - .map() 在 render 函数之外工作,但在 render 内部使用时失败

javascript - 如何在 JavaScript 中将两个依赖数组缩减为一个对象?

eclipse - hadoop 将输出写入 hdfs 文件

javascript - InnerHTML 创建问题,未按正确顺序加载,可能存在处理问题

javascript - 从 API 调用 JSON 元素并将结果作为字符串返回

javascript - 在 react 中使用 splice 添加到数组的正确方法是什么

javascript - 与/或逻辑与 .filter()

javascript - ES6 减少数组中的嵌套对象

javascript - 支持多模态单页