matt smith
matt smith

Reputation: 41

Filter array after formatting a date inside the array?

So I have an array, that I need to filter out the dates inside the array. Simply filtering it out with this:

sunday = events.filter(function(item){
  return (item.start.date == `Sunday`)
})

This works fine, the only issue is, that the date inside the array isn't formatted, the date format is as follows:

{ date: '2020-07-05' }

So how would I go about formatting that date to a weekday, then after, filter out the array dates by the now formatted date?

Edit: will put that i have been using moment to format other dates i have been using, just wasn't sure how to use the array filter with something formatted.

Upvotes: 0

Views: 777

Answers (2)

kapil pandey
kapil pandey

Reputation: 1903

Simply use :

sunday = events.filter(function(item){
let weekDay=new Date(item.start.date).toLocaleString('en-us', {weekday:'long'})
return (weekDay === "Sunday")
})

Here's an example:

const events = [
    {
        start: {
            date: '2020-07-19'
        }
    },
    {
        start: {
            date: '2020-07-20'
        }
    },
    {
        start: {
            date: '2020-07-21'
        }
    },
    {
        start: {
            date: '2020-07-22'
        }
    },
    {
        start: {
            date: '2020-07-26'
        }
    }

]
const sunday = events.filter(function(item){
let weekDay=new Date(item.start.date).toLocaleString('en-us', {weekday:'long'})
return (weekDay === "Sunday")
})
console.log("Array of sundays :", sunday)

Upvotes: 1

Dinesh Nadimpalli
Dinesh Nadimpalli

Reputation: 1491

One possible approach is take an array of week days

weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']

Assuming that your object is something like this

eventsArr = [
    {
        start: {
            date: '2020-07-05'
        }
    },
    {
        start: {
            date: '2020-07-06'
        }
    },
    {
        start: {
            date: '2020-07-07'
        }
    },
    {
        start: {
            date: '2020-07-08'
        }
    },
    {
        start: {
            date: '2020-07-09'
        }
    }

]

You can use the below code

eventsArr.filter(item => weekDays[new Date(item.start.date).getDay()]==='Sunday')

where you pass your date string to new Date() and getDay() method will give you the index of the week day which you can use to get the Week day from weekDays array to filter the data.

Upvotes: 1

Related Questions