'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 1:[1]
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];
}
Solution 2:[2]
function evenLast(arr) {
var lastarr = arr.slice(arr.length-1)
//return lastarr;
let newarr = [];
for(i=0; i<arr.length; i++){
if(arr[i] % 2 === 0) {
newarr.push(arr[i]);
}
}
//return newarr;
var sum1 =0;
for(i=0; i<newarr.length; i++) {
var sum = newarr[0] * lastarr[0];
var sum1 = newarr[1] * lastarr[0];
//return sum;
var sum2 = sum1 + sum;
//i++;
}
return sum2;
}
console.log(evenLast([2, 3, 4, 5]))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | S Gabale |