Filter problem with 0

I’m sure this is simple, but I can’t get it! Here is the flow of a program:

  1. receives a new array (newArray)
  2. uses filter to check each item of the array, make sure it doesn’t exist in the old array (oldArray)
  3. adds the new items that pass the filter into the old array

The problem is, it doesn’t seem to work if 0 is one of the values that needs to be included. I don’t see why not, though…

const oldArray = [some stuff];
const stuffToBeAdded = newArray.filter((item) => {
if (oldArray.indexOf(item) === -1) { 
return item }
else {
return false;

By the way, this is in React, although it doesn’t work in the console, either (I “translated” it for this post). I’ll add the React code below.

updateAnswers = (answer) => {
        let recForm = "";
        if (answer) { 
        let temp = quizData[this.state.currentQuestion].form; //form numbers to add to state
        recForm = temp.filter((item) => {
         if (this.state.recForms.indexOf(item) === -1) { //only add items that don't already exist in the array
            return item;
                } else {
                    return false;
        this.setState((prevState) => ({ 
            answers: prevState.answers + answer,
            currentQuestion: prevState.currentQuestion + 1,
            recForms: [...prevState.recForms, ...recForm] //adds any new items (might be in array) to the old array

I haven’t taken a close look, but the filter method callback should return either true of false, and if you return a value of 0 which evaluates to false, maybe that’s what’s messing it up?

I didn’t take closer look either. But why not ...filter(item => oldArray.indexOf(item) === -1) if you are extracting matches?

And if you need to return for each array item- as your code insinuates - you should probably use

1 Like

What @jdisco says. If you return ìtem instead of true, and ìtem is a number, then what you’re returning is coerced to true for every number except 0, which is falsey so gets coerced to false. just return true and it’ll work fine.

1 Like

Thanks everyone, got it sorted thanks to your replies. Don’t use filter too much and I was doing it wrong!