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
This should solve it:
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
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.