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

ShibinRagh
  • 6,530
  • 4
  • 35
  • 57
  • Please share the error you are getting as well as the input and expected output. – Hassan Imam Jun 26 '19 at 11:34
  • looks like it works just fine to me – TKoL Jun 26 '19 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? – TKoL Jun 26 '19 at 11:37
  • I doubt that a `JSON response` contains `Date object`? It could be a string! See if you are overlooking it – Prasanna Jun 26 '19 at 11:37

1 Answers1

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);
Rafael Herscovici
  • 16,558
  • 19
  • 65
  • 93
  • You are using non-standard date formats. Please read [What are valid Date Time Strings in JavaScript?](https://stackoverflow.com/questions/51715259/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')`. – str Jun 26 '19 at 11:53
  • @str https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse – Rafael Herscovici Jun 26 '19 at 12:06
  • What is the syntax for adding standard Date format in Mongoose Schema? – ShibinRagh Jun 26 '19 at 14:01
  • @ShibinRagh https://stackoverflow.com/questions/7443142/how-do-i-format-dates-from-mongoose-in-node-js – Rafael Herscovici Jun 26 '19 at 14:10
  • @Dementic What is your point? `1995/06/20` is not a valid date format according to the specification. – str Jun 26 '19 at 18:53
  • @str anything without a timezone (T) is valid. – Rafael Herscovici Jun 27 '19 at 00:34
  • @Dementic That is incorrect. Only the [specified date time string formats](https://www.ecma-international.org/ecma-262/6.0/#sec-date-time-string-format) are valid. – str Jun 27 '19 at 07:06