Finding the sum of even values in an array

#1

Hi All and Happy New Year!

I’m working on trying find the sum of even values in an array (array is 1000 digits of Pi - variable is “nums”)

I’ve tried several different functions but stuck at the moment (logs an empty array)… my code is below:

let nums = [1, 4, 1, 5, 9] // and 995 more numbers
let newArr = [];

const sumEvens = nums => {
  for (let i = 0; i < nums.length; ++i) {
    if (nums[i] % 2 === 0) {
      newArr.push(nums[i]);
    }
  }
  return nums;
};
console.log(newArr);

Any hints or advice is greatly appreciated! let me know if you need any further clarification.

#2

Couple of hints:

  1. You made a function called sumEvens, where are you ever calling this function?
  2. The instructions say to find a sum, where are you summing anything?
1 Like
#3

Thanks for the reply Jon!

This was one of many attempts I made after trying to get higher order functions to work - I tried to burn it all down and then just write a for loop, but I lost sight of what I was trying to accomplish at that point. Funny that I didn’t even include a way to add up the numbers, but just when you pointed that out it made me realize I could just use reduce on the array to get the sum.

I went back to using higher order functions filter and reduce and was able to accomplish the task.

// first create a variable that takes in "nums" from previous exercise and use filter to get just the even numbers in the array
const even = function(nums) {
  return nums % 2 === 0;
};
// declaring sumEvens to do the actual filtering
const sumEvens = nums.filter(even);
// declaring reducedSumEven to use reduce() and get the sum of the array
const reducedSumEven = (acc, currVal) => acc + currVal;
// log the result
console.log(sumEvens.reduce(reducedSumEven));
#5

methods like filter and reduce are chainable so you can do this whole idea even shorter

return nums
    .filter(num => num % 2 === 0) //array of evens
    .reduce((acc, currVal) => acc + currVal) // sum of filtered array
#6

or the reduce only version

return nums.reduce((acc, currVal)  => {
    if (currVal % 2 === 0) {
        return acc + currVal
    } else {
        return acc
    }
}, 0)
1 Like