2

I have an array of random integers like this: [ 1, 2, 3, 4, 0 ], I need to return a new array of either the odd or the even numbers depending on a wanted condition.

I tried the following filter method:

const result = array.filter(item => {
    const test = item % 2;
    if(wanted === 'odd' && test > 0) return item;
    if(wanted === 'even' && test === 0) return item;
  })

and had expected this to work but it only ever returns [2, 4] and never [0, 2, 4] when the wanted is even.

Any thoughts on why this might be the case would be greatly appreciated.

1
  • test will always be either 1 or 0. Testing > 0 is confusing when you're really just looking for 1. Commented Sep 28, 2018 at 23:20

1 Answer 1

2

You need to return a boolean from your filter callback, not the item. When you return the item it mostly works, but if the item is zero, that's interpreted as false

let arr = [ 1, 2, 3, 4, 0 ]
let wanted = 'even'
const result = arr.filter(item => {
    const test = item % 2;
    if(wanted === 'odd' && test > 0) return true;
    if(wanted === 'even' && test === 0) return true;
  })
console.log(result)

You can simplify any just returning the booleans created by your tests:

let arr = [ 1, 2, 3, 4, 0 ]
let wanted = 'even'
const result = arr.filter(item => {
    if (wanted === 'odd') return item % 2
    if (wanted === 'even') return !(item % 2) 
  })
console.log(result)

Sign up to request clarification or add additional context in comments.

3 Comments

You can simplify it even more using XOR (binary XOR in fact, which works because the values used are 0s and 1s): arr.filter(item => wanted === "odd" ^ item % 2)
I would have never thought of that @ibrahimmahrir. That's pretty cool.
Thanks guys, that is really helpful and has upgrade my understanding of filter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.