如何从数组中获取多个键之间的最大值 [英] how to get maximum of value between multiple keys from array
本文介绍了如何从数组中获取多个键之间的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经尝试过以下方法只有三个(不是多个)键。
I have tried this below method for only three(not multiple) keys.
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
但它没有用。是否有任何一行代码可用于从数组中获取多个键之间的最大值?
推荐答案
数组#map
每个对象的最大值,然后找到数组的最大值:
Array#map
each object to it's maximum value, then find the maximum of the array:
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);
如果你想要更灵活的东西可以接受多个键:
If you want something more flexible that can accept multiple keys:
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']));
这篇关于如何从数组中获取多个键之间的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文