want to filter even index items of array multiply with the last item of array

i have following JavaScript code

const evenLast = arr => {
  return arr.filter((a,idx) => {
   if(!(idx&1)) return (a * arr[arr.length-1])

console.log(evenLast([2, 3, 4, 5]))

and in the console i get [2,4] instead of [10, 20]

i want to know why

if(!(idx&1)) return (a * arr[arr.length-1])

returns (a) not (a * last item) of array

thanx in advance

>Solution :

This should solve it:

function main(arr){
    return arr.reduce((total, a, idx) => {
        if(!(idx & 1)){
            total.push(a * arr[arr.length - 1]);

        return total;
    }, []);

Why it happened is because filter evaluates the callback’s result and based on what it receives, it either includes the item at current index or not. So your instruction in if statement will always evaluate to true regardless of which index, (an edge case where the item at index is zero) therefore only includes the item as opposed to perform what you are intending to

Leave a Reply