Even index sum in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of integers. Our function should return the sum of all the integers that have an even index, multiplied by the integer at the last index.

const arr = [4, 1, 6, 8, 3, 9];

Expected output −

const output = 117;

Example

Following is the code −

 Live Demo

const arr = [4, 1, 6, 8, 3, 9];
const evenLast = (arr = []) => {
   if (arr.length === 0) {
      return 0
   } else {
      const sub = arr.filter((_, index) => index%2===0)
      const sum = sub.reduce((a,b) => a+b)
      const posEl = arr[arr.length -1]
      const res = sum*posEl
      return res
   }
}
console.log(evenLast(arr));

Output

Following is the console output −

117

Updated on: 17-Apr-2021

483 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements