[英]compare multidimensional array to find array with largest value javascript
I have a multidimensional array that has name and integer values in them. 我有一个多维数组,其中包含名称和整数值。 I need to be able to compare the integer value in each array in the multidimensional array. 我需要能够比较多维数组中每个数组中的整数值。 how can I compare and return that array? 我该如何比较并返回该数组?
var totals = [
['john', 'test', 45],
['bob', 'tester', 75]
];
How can I loop over the arrays in the "totals" array and return the one with the largest integer value? 如何在“totals”数组中循环遍历数组并返回具有最大整数值的数组?
You could use reduce . 你可以使用reduce 。 For example: 例如:
var totals = [
['john', 'test', 45],
['john', 'test', 46],
['john', 'test', 42],
['john', 'test', 41]
];
var biggest = totals.reduce((a, b) => a[2] > b[2] ? a : b);
console.log(biggest);
It should be noted, that if reduce()
is not supplied with an initial value, then a
becomes the first, and b
becomes the second in the first call. 应该注意的是,如果reduce()
没有提供初始值,则a
成为第一个, b
成为第一个调用中的第二个。
var largest = totals.reduce((prev, cur) => prev[2] > cur[2] ? prev : cur, [0,0,0]);
var result = totals.reduce((p, c) => {
return p[2] > c[2] ? p : c;
});
console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.