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
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.
function maxValues(array) {
var maxArray = [];
var length = array[0].length;
for (var i = 0; i < length; i++) {
var ithColumn = [].map.call(array, function(array) {
return array[i];
});
maxArray.push(Math.max.apply(null, ithColumn));
}
return maxArray;
}
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));
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);
I took Tom Panning's answer and simplified it even further:
var A = [[2.2, 3.3, 1.3], [1.2, 5.3, 2.2], [0.3, 2.2, 5.2]];
var MAX = _.zip.apply(null, A).map(_.max);
var data = [
[2.2, 3.3, 1.3],
[1.2, 5.3, 2.2],
[0.3, 2.2, 5.2]
];
function maxAtIndex (data) {
//output
var maxArray = [];
//loop arrays passed in
for (var i = 0; i < data[0].length; i++) {
var possibleValues = [];
//get value in array at index
for (var j = 0; j < data.length; j++) {
possibleValues.push(data[j][i]);
}
//get the highest from possible values
var 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 ]
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.