skip to Main Content

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]))

In the console, I get [2,4] instead of [10, 20] and I want to know why if(!(idx&1)) return (a * arr[arr.length-1]) returns (a) rather than (a * last_item_of_array).

2

Answers


  1. 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

    Login or Signup to reply.
  2. Array.filter is for reducing an array to a smaller subset. Array.map is for returning a new array. What you need to do is combine them.

    const evenRow = (_, idx) => {
      return idx&1;
    };
    
    const calculate = (val, _, arr) => {
      return val * arr.at(-1);
    };
    
    const evenLast = arr => {
    
      return arr.filter( evenRow ).map( calculate );
    
    };
    
    console.log( evenLast([2, 3, 4, 5]) );
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search