Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 arrays of numbers. Our function should return an array of greatest numbers picked from the corresponding positions of the input arrays. The number of elements in the output array should be equal to the length of the longest input array.
Problem Understanding
Given multiple arrays, we need to compare elements at the same index positions and select the maximum value from each position to form a new 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
[ 900, 332, 432, 145 ]
How It Works
The function iterates through each array and compares elements at corresponding indices. At each position, it keeps the maximum value found so far:
- Position 0: max(117, 132, 32, 900) = 900
- Position 1: max(121, 19, 23, 332) = 332
- Position 2: max(18, 432, 137, 23) = 432
- Position 3: max(24, 23, 145, 19) = 145
Alternative Approach Using Math.max
Here's a cleaner implementation using Math.max():
const mergeGreatestV2 = (...arrs) => {
const maxLength = Math.max(...arrs.map(arr => arr.length));
const result = [];
for (let i = 0; i < maxLength; i++) {
const valuesAtIndex = arrs.map(arr => arr[i] || -Infinity);
result[i] = Math.max(...valuesAtIndex);
}
return result;
};
console.log(mergeGreatestV2(arr1, arr2, arr3, arr4));
[ 900, 332, 432, 145 ]
Handling Arrays of Different Lengths
const arr1 = [10, 20]; const arr2 = [5, 15, 25]; const arr3 = [8, 12, 18, 30]; console.log(mergeGreatestV2(arr1, arr2, arr3));
[ 10, 20, 25, 30 ]
Conclusion
This function efficiently combines multiple arrays by selecting the maximum value at each index position. The alternative approach using Math.max() provides better readability and handles arrays of different lengths more gracefully.
