0

This problem is quite easy but I still can't handle it. I have an array of object let's say something like:

const array = [{id:1,created_at: 2022-03-14T16:40:10.000000Z}, {id:2, created_at:2022-03-15T16:40:10.000000Z}

I want to filter element using moment.js, and having back only the element that have date of creation of today.

What i want to achieved is something like this:

const filtered = array.filter((item)=> item.created_at >= startOfToday && item.created_at <= endOfToday

Filtered will look like: [0]{id:2, created_at:2022-03-15T16:40:10.000000Z}

Thanks in advance for any tips/answers.

Levi D.
  • 176
  • 8

2 Answers2

1

Can you use statOf and endOf to make your filter work?

const filtered = array.filter(item => {
  const createdAt = moment(item.created_at)
  const startOfToday = moment().startOf('day')
  const endOfToday = moment().endOf('day')
  return createdAt.isBetween(startOfToday, endOfToday)
})
twharmon
  • 4,153
  • 5
  • 22
  • 48
  • Doesn't seems to work, returning empty array – Levi D. Mar 16 '22 at 15:15
  • Are the items in your array from today? In your question I see March 14 and 15, but today might be March 16. – twharmon Mar 16 '22 at 15:21
  • Yes, on my array i have lot of date with 15/03 and one with 16/03, so i expect to have back one element in the filtered array – Levi D. Mar 16 '22 at 15:25
  • https://codepen.io/Levi-D/pen/xxpwLWG I left you the pen to check it – Levi D. Mar 16 '22 at 15:30
  • I fixed it @LeviD. It didn't work because `endOf` and `startOf` mutate the `Moment`. This is annoying, a bit unpredictable, and really why moment isn't maintained well anymore. – twharmon Mar 16 '22 at 15:34
  • Thank you so much, it works now! Yes, seems that moment give back a Moment object where we cannot do any comparation. – Levi D. Mar 16 '22 at 15:42
1

Solution with Pure Vanilla JavaScript

let arr = [
  { name: "Iron Man", released_on: "2002-08-21T00:00:00.000Z" },
  { name: "Captain Amoos", released_on: "2008-08-21T00:00:00.000Z" },
  { name: "Amoos John Wick", released_on: "2014-08-21T00:00:00.000Z" },
  { name: "James Bond", released_on: "2021-08-21T00:00:00.000Z" },
  { name: "Loin King", released_on: "2022-08-21T00:00:00.000Z" },
];


let fromDate = "2004-01-01";
let toDate = "2020-11-22";

const filteredData = (data, key, startDate, endDate) => {     
     startDate = new Date(startDate).getTime();
     endDate = new Date(endDate).getTime();
  
  return data.filter( d => {
    let time = new Date(d[key]).getTime();
    return ( startDate < time && time < endDate )
  });
}

console.log(
  filteredData(arr, "released_on", fromDate, toDate)
);
GMKHussain
  • 3,342
  • 1
  • 21
  • 19