Search code examples
javascriptarrayssumintegernumbers

Given a sequence of integers, return the sum of all the integers that have an even index, multiplied by the integer at the last index


This is my solution and it passes some of the tests, but not all of them. Can anyone help me and explain why? Thank you :)

function evenLast(numbers) {
  let sum = 0;
  let lastNum = numbers.pop();
  let arr = numbers.filter(el => el % 2 === 0);

  
  for(let i = 0; i < arr.length; i++) {
    sum += (arr[i] * lastNum);
  } 
  return sum;
}

Solution

  • You need to check the index, not the value

    let arr = numbers.filter((_, i) => i % 2 === 0);
    

    And you could multiply the sum at the last step.

    for (let i = 0; i < arr.length; i++) {
        sum += arr[i]);
    } 
    return sum * lastNum;
    

    A better approach takes only a single loop and sums the values by taking an increment of two.

    function evenLast(numbers) {
        let sum = 0;
    
        for (let i = 0; i < numbers.length; i += 2) sum += numbers[i];
    
        return sum * numbers[numbers.length - 1];
    }