Let's start off with a fairly simple challenge, but one that uses a few different array methods. Write a function called sumOfEvenSquares that takes an array of numbers and returns the sum of the squares of the even numbers in the array.
/**
* Returns the sum of the squares of the even numbers in the array.
* @param {number[]} numbers - The array of numbers.
* @returns {number} - The sum of the squares of even numbers.
*/
function sumOfEvenSquares(numbers: number[]): numbersumOfEvenSquares([1, 2, 3, 4, 5]); // 20 (2^2 + 4^2)
sumOfEvenSquares([-1, 0, 1, 2, 3, 4]); // 20 (0^2 + 2^2 + 4^2)
sumOfEvenSquares([]); // 0- Use the
filtermethod to select the even numbers from the array. - Then, use the
mapmethod to square each even number. - Finally, use the
reducemethod to sum up the squared even numbers.
Click For Solution
function sumOfEvenSquares(numbers) {
const evenSquares = numbers
.filter((num) => num % 2 === 0)
.map((num) => num ** 2);
return evenSquares.reduce((sum, square) => sum + square, 0);
}You can format this so many different ways. This is just one example.
-
Create a variable called
evenSquaresand set it equal to the result of calling thefiltermethod on thenumbersarray and then calling themapmethod on the result of that. -
For the
filtermethod, pass in a callback function that takes in a number and returnstrueif the number is even andfalseotherwise. We used the modulo operator (%) to check if the number is even. -
For the
mapmethod, pass in a callback function that takes in a number and returns the square of that number. Now we have an array of the squares of the even numbers. -
Finally, call the
reducemethod on theevenSquaresarray and pass in a callback function that takes in a sum and a square and returns the sum plus the square. We set the initial value of the sum to0.
We could even shorten this by chaining the methods together and using an arrow function:
const sumOfEvenSquares = (numbers) =>
numbers
.filter((num) => num % 2 === 0)
.map((num) => num ** 2)
.reduce((sum, square) => sum + square, 0);test('Sum of even squares', () => {
expect(sumOfEvenSquares([1, 2, 3, 4, 5])).toBe(20);
expect(sumOfEvenSquares([-1, 0, 1, 2, 3, 4])).toBe(20);
expect(sumOfEvenSquares([])).toBe(0);
});