0

JSON response from the server and I need to filter with the date(year) before to show client-side

example

person = [{ name: String, birth: Date }]



function fltr(name, year){
   return person.filter(res => ( res.name == name && res.birth.getFullYear() === year) )
}

fltr('jon', 1990 );

added getFullYear() in condition res.birth.getFullYear() to match with year but not working , Please correct me

Please

4
  • Please share the error you are getting as well as the input and expected output. Commented Jun 26, 2019 at 11:34
  • looks like it works just fine to me Commented Jun 26, 2019 at 11:36
  • You say you get json from the server -- JSON cannot encode dates, so you have to manually iterate over your person array and change the date strings into javascript date objects. Have you done this already? Commented Jun 26, 2019 at 11:37
  • I doubt that a JSON response contains Date object? It could be a string! See if you are overlooking it Commented Jun 26, 2019 at 11:37

1 Answer 1

2

i would guess your date format is wrong, since the following works pretty well:

const people = [{ name: 'Kaiser Soze', birthDate: '1995/06/20' }];
const filterByNameAndBirthYear = (name, year) => {
  return people.filter(person => person.name === name && new Date(person.birthDate).getFullYear() === year);
}
let result = filterByNameAndBirthYear('Kaiser Soze', 1995);
console.log(result);

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

7 Comments

You are using non-standard date formats. Please read What are valid Date Time Strings in JavaScript?. For example, new Date('1995/06/20') is not the same as new Date('1995-06-20').
What is the syntax for adding standard Date format in Mongoose Schema?
@Dementic What is your point? 1995/06/20 is not a valid date format according to the specification.
|

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.