javascript - 如何获取数组中多个键之间的最大值

标签 javascript angularjs arrays angular typescript

如何获取数组中多个键之间的最大值?

我已经针对仅三个(不是多个)键尝试了以下方法。

getMaxValuefromkeys(values: any[], key1: string, key2: string, key3: string) {
    var val1 = Math.max.apply(Math, values.map(function (a) { return a[key1] }));
    var val2 = Math.max.apply(Math, values.map(function (a) { return a[key2]; }));
    var val3 = Math.max.apply(Math, values.map(function (a) { return a[key2]; }));
    if (val1 >= val2 || val1 >= val3) {
        return val1;
    } else if (val2 >= val3 || val2 >= val1) {
        return val2;
    }
    return val3;
}

But we need to check more condition and write more codes if we use multiple keys. So I have tried these below codes

Math.max.apply(Math, values.map(function (a) { return a[key1], a[key2], a[key3]; }));
                                         // where I want to return multiple keys 

But it's not working. Is any single line of code available for getting max value in between multiple keys from array?

最佳答案

Array#map 每个对象到它的最大值,然后找到数组的最大值:

var values = [{ a: 4, b: 3 }, { a: 2, b: 8 }, { a: 1, b: 2 }];

var key1 = 'a', key2 = 'b';

var result = Math.max.apply(Math, values.map(function (a) { return Math.max(a[key1], a[key2]); }));

console.log(result);

如果你想要更灵活的可以接受多个键的东西:

var values = [{ a: 4, b: 3, c: 23 }, { a: 2, b: 28, c: 13 }, { a: 1, b: 2, c: 1 }];

function getMaxOfKeys(values, keys) {
  return Math.max.apply(Math, values.map(function(obj) {
    return Math.max.apply(Math, keys.map(function(key) {
      return obj[key];
    }));
  }));
}

// or the ES6 equivalent

const getMaxOfKeysES6 = (values, keys) => 
  Math.max(...values.map(
    (obj) => 
      Math.max(...keys.map((key) => obj[key]))
    )
  );

console.log(getMaxOfKeys(values, ['a', 'b', 'c']));
console.log(getMaxOfKeysES6(values, ['a', 'b', 'c']));

关于javascript - 如何获取数组中多个键之间的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44719783/

相关文章:

c - 在 c 中制作和发送混合 double 和整数数组

javascript - 如何使用 showdown.js 将表格文本打印到 md 表格?

angularjs - 带路由的自定义状态进入和状态退出代码

javascript - lodash .each 和 .trim 忽略数组元素?

javascript - 处理服务和 Controller 之间的 AngularJS Promise 的推荐方法

angularjs - 在 Angularjs 中加载新 View 后刷新 MathJax

javascript - 改变数组的元素

javascript - 需要另一个帮助来动态地在屏幕上显示文本

javascript - 选择更改时阻止多个选择滚动到顶部

javascript - JS-Ooyala API : How do I return this objects title property?