How to return specific year from Date array ? react

I’ve got a dates array and I wanted to create a function that returns all the dates from 2014 or 2015 depending on what the user clicks

i tried using substring(), although that gives me an array of the 2014 dates, it also returns 2 undefined’s which I dont want. How would I return an array of only 2014 dates?

const datefunc = () => {
  const date = ['2014-4-4', '2014-5-4', '2015-4-4', '2015-3-4']

  const dates = date.map((d) => {
    if (d.substring(0, 4) === '2014') {
      return d;
    }
  })

  console.log(dates)
}

datefunc()

Answer

Array.map modifies each element in an array => when you run date.map and only return a value if the date starts with ‘2014’, all the other values in the array will become undefined.

Array.filter filters the elements in an array based on a predicate => when running date.filter, all the elements for which the predicate is false will be excluded in the returned array.

Changing your code to this should work:

const datefunc = () => {
  const date = ['2014-4-4', '2014-5-4', '2015-4-4', '2015-3-4'];

  const dates = date.filter((d) => d.substring(0, 4) === '2014');

  // You could also use this
  // const dates = date.filter((d) => d.startsWith('2014'));

  console.log(dates);
  
}

datefunc();

If your dates aren’t all of the same form, but all valid date strings you could also tranfsorm them into Date values and then filter them like this:

const datefunc = () => {
  const date = ['2014-4-4', '2014-5-4', '2015-4-4', '2015-3-4'];

  const dates = date
    .map((d) => new Date(d))
    .filter((d) => d.getFullYear() === 2014);

  console.log(dates);
}

datefunc();