JavaScript: Combine highest key values of multiple arrays into a single array


We are required to write a JavaScript function that takes in any number of array of Numbers. Our function should return an array of greatest numbers picked from the input array of array. The number of elements in the output array should be equal to the number of subarrays contained in the original input array.

Example

The code for this will be −

const arr1 = [117, 121, 18, 24];
const arr2 = [132, 19, 432, 23];
const arr3 = [32, 23, 137, 145];
const arr4 = [900, 332, 23, 19];
const mergeGreatest = (...arrs) => {
   const res = [];
   arrs.forEach(el => {
      el.forEach((elm, ind) => {
         if(!( res[ind] > elm)) {
            res[ind] = elm;
         };
      });
   });
   return res;
};
console.log(mergeGreatest(arr1, arr2, arr3, arr4));

Output

And the output in the console will be −

[ 900, 332, 432, 145 ]

Updated on: 21-Nov-2020

162 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements