When summing values from 2 arrays how can I cap the value in the new JavaScript array?

JavascriptWeb DevelopmentObject Oriented Programming

Suppose, we have two arrays both containing three elements each, the corresponding values of red, green, blue color in integer.

Our job is to add the corresponding value to form an array for new rgb color and also making sure if any value adds up to more than 255, we that value to 255.

Therefore, let’s define a function addColors() that takes in two arguments, both arrays and returns a new array based on the input.

The code for this will be −

Example

const color1 = [45, 125, 216];
const color2 = [89, 180, 78];
const addColors = (color1, color2) => {
   const newColor = color1.map((val, index) => {
      return val + color2[index] <= 255 ? val + color2[index] : 255;
   })
   return newColor;
};
console.log(addColors(color1, color2));

Output

The console output will be −

[ 134, 255, 255 ]

We map over the first color, add the corresponding value of the second color to it, if the value exceeds 255, we return 255 otherwise we return the added value. So in this way the addColors() function will do the job for us.

raja
Published on 18-Aug-2020 11:11:58
Advertisements