Horje
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:

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.

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.

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



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
Check Whether a Year is a Palindrome Year using JavaScript Check Whether a Year is a Palindrome Year using JavaScript
How to get the Value by a Key in JavaScript Map? How to get the Value by a Key in JavaScript Map?
Print Strong Numbers Within a Range using JavaScript Print Strong Numbers Within a Range using JavaScript
TypeScript Array.from() Method TypeScript Array.from() Method
How to use Type Guards in TypeScript ? How to use Type Guards in TypeScript ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12