Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading