Home > Enterprise >  How to filter an array by year using the format DD/MM/YYYY
How to filter an array by year using the format DD/MM/YYYY

Time:09-29

I have this code below :

  var array1 = ['10/10/2020','11/10/2020','12/10/2020','10/10/2021','12/10/2021','12/10/2021'];

  <select id="dates">
    <option>2021</option>
    <option>2020</option>
  </select>

I would like to know how can I filter the array1 to return just the values from the year selected. Any Suggestion ?

CodePudding user response:

I hope this code helping you

var result = array1.filter(o=>o.indexOf('2021') != -1)

CodePudding user response:

You can take help from Array filter method

const result = array1.filter(date => date.includes(2021))

above result will give you all the dates with the year 2021

CodePudding user response:

Listen for the change event and use Array.filter to filter out the items whether the year isn't the same as the select's value.

You can get the year by splitting the string by a slash and getting the third item.

var array1 = ['10/10/2020', '11/10/2020', '12/10/2020', '10/10/2021', '12/10/2021', '12/10/2021'];

dates.addEventListener("change", function(){
  var filtered = array1.filter(e => e.split("/")[2] == this.value)
  console.log(filtered)
})
<select id="dates">
  <option>2021</option>
  <option>2020</option>
</select>

  • Related