Search code examples
javascriptarraysdatearray-filter

I am working on array filters. i am stuck with adding filters to date


I stored data in an array and I would like to make array filter with date parameter.

Example:

date.filter(obj => obj.date >= '2020-09-01 00:00:01 UTC' && obj.date <= '2020-09-05 23:59:59 UTC')

Then I need to see the record length between these dates, in above example, 5.

Code

<!DOCTYPE html>
<html>
<body>
<script>
let orders = [
  {  amount: '100', user: 'admin', date: '2020-09-01 00:00:01 UTC' },
  {  amount: '120', user: 'admin', date: '2020-09-02 00:00:01 UTC' },
  {  amount: '80',  user: 'admin', date: '2020-09-03 00:00:01 UTC' },
  {  amount: '200', user: 'admin', date: '2020-09-04 00:00:01 UTC' },
  {  amount: '200', user: 'admin', date: '2020-09-05 00:00:01 UTC' },
  {  amount: '200', user: 'admin', date: '2020-09-06 00:00:01 UTC' },
  {  amount: '200', user: 'admin', date: '2020-09-07 00:00:01 UTC' },
  {  amount: '200', user: 'admin', date: '2020-09-08 00:00:01 UTC' },
  {  amount: '200', user: 'admin', date: '2020-09-09 00:00:01 UTC' },
  {  amount: '200', user: 'admin', date: '2020-09-10 00:00:01 UTC' },
  {  amount: '200', user: 'admin', date: '2020-09-11 00:00:01 UTC' },
];

console.log(orders)
</script>
</body>
</html>

Thanks in advance


Solution

  • You need to convert the date strings into actual Date objects

    const orders = [
      {  amount: '100', user: 'admin', date: '2020-09-01 00:00:01 UTC' },
      {  amount: '120', user: 'admin', date: '2020-09-02 00:00:01 UTC' },
      {  amount: '80',  user: 'admin', date: '2020-09-03 00:00:01 UTC' },
      {  amount: '200', user: 'admin', date: '2020-09-04 00:00:01 UTC' },
      {  amount: '200', user: 'admin', date: '2020-09-05 00:00:01 UTC' },
      {  amount: '200', user: 'admin', date: '2020-09-06 00:00:01 UTC' },
      {  amount: '200', user: 'admin', date: '2020-09-07 00:00:01 UTC' },
      {  amount: '200', user: 'admin', date: '2020-09-08 00:00:01 UTC' },
      {  amount: '200', user: 'admin', date: '2020-09-09 00:00:01 UTC' },
      {  amount: '200', user: 'admin', date: '2020-09-10 00:00:01 UTC' },
      {  amount: '200', user: 'admin', date: '2020-09-11 00:00:01 UTC' },
    ];
    
    const getOrdersBetween = (orders, start, end) => orders.filter(({ date }) => new Date(date) >= new Date(start) && new Date(date) <= new Date(end));
    
    const result = getOrdersBetween(orders, '2020-09-01 00:00:01 UTC', '2020-09-05 23:59:59 UTC');
    
    console.log(result);