Sum of Squares of Even Numbers in an Array using JavaScript
JavaScript program allows us to compute the sum of squares of even numbers within a given array. The task involves iterating through the array, identifying even numbers, squaring them, and summing up the squares.
There are several approaches to find the sum of the square of even numbers in an array using Javascript which are as follows:
Table of Content
- Iterative Approach
- Using Array Methods
Iterative Approach
In this approach, we iterate through the array and for each element, check if it’s even. If it is, we calculate its square and add it to the sum.
Example: The below code Find Sum of Squares of Even Numbers in an Array using the iterative approach in JavaScript.
function sumOfSquaresOfEvenNumbers(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] % 2 === 0) {
sum += arr[i] * arr[i];
}
}
return sum;
}
const numbers = [1, 2, 3, 4, 5, 6, 67, 8];
console.log(sumOfSquaresOfEvenNumbers(numbers));
Output
120
Using Array Methods
JavaScript Array methods like filter() allows us to filter out the even numbers and reduce() is used to calculate the sum of squares.
Example: The below code Find Sum of Squares of Even Numbers in an Array using array methods in JavaScript.
function sumOfSquaresOfEvenNumbers(arr) {
return arr.filter(num => num % 2 === 0)
.reduce((acc, curr) => acc + curr * curr, 0);
}
const numbers = [1, 2, 3, 4, 5, 6];
console.log(sumOfSquaresOfEvenNumbers(numbers));
Output
56
Contact Us