Skip to content Skip to sidebar Skip to footer

Find Max Value Comparing Multiple Arrays For Each Index

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 val

Solution 1:

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);

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.

Solution 2:

vardata = [
    [2.2, 3.3, 1.3],
    [1.2, 5.3, 2.2],
    [0.3, 2.2, 5.2]
];

function maxAtIndex (data) {
    //outputvar maxArray = [];
    //loop arrays passed infor (var i = 0; i < data[0].length; i++) {
        var possibleValues = [];
        //get value in array at indexfor (var j = 0; j < data.length; j++) {
            possibleValues.push(data[j][i]);
        }
        //get the highest from possible valuesvar highest = Math.max.apply(null, possibleValues);
        //store in output array
        maxArray.push(highest);
    }
    return maxArray;
};

console.log(maxAtIndex(data)); //[ 2.2, 5.3, 5.2 ]

Solution 3:

For each index of the array, create an array containing all elements in the "column" and find the max of those values. Return the generated array. Sample usage: maxValues(A) would give the desired result.

functionmaxValues(array) {
    var maxArray = [];
    var length = array[0].length;
    for (var i = 0; i < length; i++) {
        var ithColumn = [].map.call(array, function(array) {
            returnarray[i];
        });
        maxArray.push(Math.max.apply(null, ithColumn));
    }
    return maxArray;
}

Solution 4:

You can combine Lo-Dash's zip and map methods to do this in just a few lines of code:

var A = [[2.2, 3.3, 1.3], [1.2, 5.3, 2.2], [0.3, 2.2, 5.2]];

// Creates an array of arrays, where the first array is all the first elements,// the second array is all the second elements, etc.var zipped = _.zip(A);
var maxes = _.map(zipped, function(arr) {
    return _.max(arr);
});
console.log(maxes);

Solution 5:

Here's a short and sweet version:

var A = [[2.2, 3.3, 1.3], [1.2, 5.3, 2.2], [0.3, 2.2, 5.2]];

var maxA = A.map(a => Math.max.apply(null, a));

Post a Comment for "Find Max Value Comparing Multiple Arrays For Each Index"