Robert Maxwell
Robert Maxwell

Reputation: 23

Loop through 3 arrays and get largest value for each index position only if there is a value in 3rd array otherwise return 0

Is there a function to loop through multiple arrays and get largest value for each index position only if there is a value in the last array otherwise return 0?

I have used a solution in Find max value comparing multiple arrays for each index for the part where I can get the max value but need it only if there is a value in the last array.

Here's an example of what I'm after:

array1 = [3,54,2,0],
array2 = [33,6,1,0],
array3 = [0,1,1,11];

result = [0,54,2,11]

Upvotes: 1

Views: 304

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386710

You could use a check and map and reduce from right side, with Array#reduceRight

It starts with from the right side of the array and respect zero values. If it starts with a zero value, the zero value is used as the result value.

     r  [ 0,  1,  1, 11]
     a  [33,  6,  1,  0]
------  ----------------
     r  [ 0,  6,  1, 11]
     a  [ 3, 54,  2,  0]
------  ----------------
result  [ 0, 54,  2, 11]
         ^^
         column with zero as start value

var arrays = [[3, 54, 2, 0], [33, 6, 1, 0], [0, 1, 1, 11]],
    result = arrays.reduceRight(function (r, a) {
        return r.map(function (b, i) {
            return b && Math.max(b, a[i]) || 0;
        });
    });

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

ES6

var arrays = [[3, 54, 2, 0], [33, 6, 1, 0], [0, 1, 1, 11]],
    result = arrays.reduceRight((r, a) => r.map((b, i) => b && Math.max(b, a[i]) || 0));

console.log(result);

Upvotes: 1

Redu
Redu

Reputation: 26191

You may do as follows for arbitrary number of arrays in the same length;

var arrs = [[3,54,2,0],[33,6,1,0],[0,1,1,11]],
result   = arrs.reduce((p,c,i,a) => i < a.length-1 ? p.map((n,j) => n > c[j] ? n : c[j])
                                                   : p.map((n,j) => n > c[j] && c[j] ? n : c[j]));
console.log(result);

Upvotes: 0

alpheus
alpheus

Reputation: 240

var result = [];
for(var i in array1.length) {
    if (!array3[i]) {
         result.push(0);
    }
    else {
         result.push(Math.max(array1[i], array2[i], array3[i]));
    }
}
console.log(result);

Upvotes: 0

Related Questions