查找比较每个索引的多个数组的最大值 [英] Find max value comparing multiple arrays for each index

查看:89
本文介绍了查找比较每个索引的多个数组的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种方法来找到最大值,比较数组中每个观察的多个(未知数,但相同长度)数组,返回一个具有最大值的数组。

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.

这篇关于查找比较每个索引的多个数组的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆