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

When working with arrays that represent RGB color values, you often need to add corresponding elements while ensuring the result doesn't exceed the maximum value of 255. This is a common requirement in graphics programming and color manipulation.

Suppose we have two arrays, each containing three elements representing the red, green, and blue color values as integers. Our goal is to add the corresponding values to form a new RGB color array, capping any value that exceeds 255.

Problem Statement

We need to create a function that:

  • Takes two arrays as input (representing RGB values)
  • Adds corresponding elements from both arrays
  • Caps any result greater than 255 to exactly 255
  • Returns a new array with the processed values

Solution Using Array.map()

The most efficient approach uses the map() method with a conditional operator to cap values:

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));
[ 134, 255, 255 ]

How It Works

The function maps over the first color array and for each element:

  1. Adds the corresponding value from the second array
  2. Checks if the sum exceeds 255
  3. Returns the sum if it's ? 255, otherwise returns 255

In our example:

  • Red: 45 + 89 = 134 (? 255, so keep 134)
  • Green: 125 + 180 = 305 (> 255, so cap to 255)
  • Blue: 216 + 78 = 294 (> 255, so cap to 255)

Alternative Using Math.min()

You can also use Math.min() for cleaner code:

const addColorsWithMath = (color1, color2) => {
    return color1.map((val, index) => Math.min(val + color2[index], 255));
};

const color1 = [45, 125, 216];
const color2 = [89, 180, 78];

console.log(addColorsWithMath(color1, color2));
[ 134, 255, 255 ]

Comparison

Method Readability Performance
Conditional operator Good Slightly faster
Math.min() Better Good

Conclusion

Both approaches effectively cap array values during addition. The Math.min() method offers cleaner, more readable code, while the conditional operator provides slightly better performance for large datasets.

Updated on: 2026-03-15T23:18:59+05:30

170 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements