
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Cap Values When Summing Two Arrays in JavaScript
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.
Advertisements