查找比较每个索引的多个数组的最大值
问题描述:
我正在尝试找到一种方法来找到最大值,比较数组中每个观察的多个(未知数,但相同长度)数组,返回一个具有最大值的数组。
I'm trying to find a method to find the max value comparing multiple(unknown number, but same length) arrays for each observation in the arrays, returning an array with the max values.
示例:
编辑:
A = [[2.2, 3.3, 1.3], [1.2, 5.3, 2.2], [0.3, 2.2, 5.2], etc......]
退货
MAX = [2.2, 5.3, 5.2]
能够检查'输入' -arrays长度相同,但无法比较找到最大值的数组....
Able to check that the 'input'-arrays are of the same length, but not able to compare the arrays finding the max....?
答
你可以使用 Array.reduce()
:
You could use Array.reduce()
:
var A = [[2.2, 3.3, 1.3], [1.2, 5.3, 2.2], [0.3, 2.2, 5.2]];
var max = A.reduce(function(final, current) {
for (var i = 0; i < final.length; ++i) {
if (current[i] > final[i]) {
final[i] = current[i];
}
}
return final;
});
console.log(max);
内部函数比较当前最大值使用下一个数组元素,因此 final
始终保持到目前为止遍历的所有元素的最大值。
The inner function compares the current maximum with the next array element and so final
always holds the maximum value for all elements traversed thus far.