skip to Main Content

I’m expecting to filter an array with a date attribute, and even though I’m getting the same equal values the new array isn’t created.

let array = [...]

state.newArray = array.filter((f) => { 
  let newDepartDate = new Date(f.depart_date); 
  console.log( newDepartDate.getDate());   // returns 17 
  console.log( data.getDate());   // returns 17 
  newDepartDate.getDate() === data.getDate(); 
});

2

Answers


  1. Array.prototype.filter() expects a boolean value to determine whether to include the element in the filtered array or not.

    You have to return the result of the comparison from the filter callback.

    ...
    return newDepartDate.getDate() === data.getDate();
    ...
    

    Please Note: When adding multiple statements in a callback function using curly braces {}, you need to specify the return keyword to explicitly return a value from the callback.

    If you don’t specify the return keyword, the callback function will implicitly return undefined.

    Login or Signup to reply.
  2. When using array.filter, if your function is more than just a single expression, you need to write the return value. Try adding return at the end:

    let array = [...]
    
    state.newArray = array.filter((f) => { 
        let newDepartDate = new Date(f.depart_date); 
        console.log( newDepartDate.getDate());   // returns 17 
        console.log( data.getDate());   // returns 17 
        return newDepartDate.getDate() === data.getDate(); 
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search