0

I want to build a function that adds the even positions of an array, but without repeating them

i.e : arr = [1, 2, 8, 3, 2, 3 ,4] should return 14 (2+8+4)

For the addition part I have it more or less clear :

result = arr.reduce(getSum, 0);
    function getSum(a, b) {
        return a + b
    } 

To find the even numbers, I came up with this

function addEvenNum(anyArray) {
    let evenNum = [];
    for (i = 0; i < anyArray.length; i++) {

        if (anyArray[i] % 2 == 0) {
           evenNum.push(anyArray[i]);            
         }
      }
   }
addEvenNum(arr) 

With these function I get let evenNum = [2,8,2,4] , but i am not sure how to remove the repeated number. I can only think about another nested loop to iterate over it, and find the repeteated one and remove it . Something like this :

for (j = 0; j < evenNum.length; j++) {

            let index = evenNum.indexOf(j)

                if (index < -1) {
                 evenNum.splice (index, 1)
                }
            }

but i think I am far away from it ...and even if it worked, not sure how to put all toghether in once function that doesnt have like 60 lines...

(sorry if my question is a bit messy ...my head is like that right now)

notADevYet
  • 307
  • 2
  • 13

0 Answers0