user13780186
user13780186

Reputation:

How to filter/reduce the data based on the latest date

data = {
 start: 1,
 data: [
  {
   name: 'Juan',
   date: '2020-01-19
  },
  {
   name: 'Carlo',
   date: '2020-03-01
  },
  {
   name: 'Dela',
   date: '2020-03-01
  },
  {
   name: 'Cruz',
   date: '2021-04-01
  }
 ],
 totalRecords: 19
}

What I'm trying to do filter the data to the latest date which is 2020-04-01.

What I tried is like this:

response['data']['data'] = response['data']['data'].filter(item => {
           return item['date'] > '2020-04-01';
         });

But it doesn't work.

Expected output should be like this

data = {
 start: 1,
 data: [
  {
   name: 'Cruz',
   date: '2021-04-01
  }
 ],
 totalRecords: 19
}

Upvotes: 2

Views: 1025

Answers (3)

Nguyễn Văn Phong
Nguyễn Văn Phong

Reputation: 14198

Other answers exist some problems (in terms of performance, expected output).

  1. You shouldn't use sort because time complexity will take at least O(nlogn).
  2. Using filter will return more than one lastItem

==> So you can use Array#reduce (with time complexity is just O(n)) like this.

const comparedDate = new Date('2020-04-01')
const response = {
 start: 1,
 data:[{name:'Juan',date:'2020-01-19'},{name:'Carlo',date:'2020-03-01'},{name:'Dela',date:'2020-03-01'},{name:'Cruz',date:'2021-04-01'}],
 totalRecords:19};

const lastData = response.data.reduce((acc, curr) => {
  if(new Date(curr.date) > comparedDate)
    acc = curr;
  
  return acc;
}, response.data[0]);

console.log(lastData);

In case that you want to result in multiple items <= 2020-04-01, you can do like this

const comparedDate = new Date('2020-04-01')
const response = {
 start: 1,
 data:[{name:'Juan',date:'2020-01-19'},{name:'Carlo',date:'2020-03-01'},{name:'Dela',date:'2020-03-01'},{name:'Cruz',date:'2021-04-01'}],
 totalRecords:19};

response.data = response.data.reduce((acc, curr) => {
  if(new Date(curr.date) >= comparedDate)
    acc.push(curr);
  
  return acc;
}, []);
console.log(response);

Upvotes: 1

Shivam Singla
Shivam Singla

Reputation: 2201

You need to convert the date strings into Date objects.

const checkDate = new Date('2020-04-01')
const response = {
 start: 1,
 data: [
  {
   name: 'Juan',
   date: '2020-01-19'
  },
  {
   name: 'Carlo',
   date: '2020-03-01'
  },
  {
   name: 'Dela',
   date: '2020-03-01'
  },
  {
   name: 'Cruz',
   date: '2021-04-01'
  }
 ],
 totalRecords: 19
}

response.data = response
  .data
  .filter(({date}) => new Date(date) > checkDate)
  
console.log(response)

Upvotes: 1

Alex D
Alex D

Reputation: 692

You can use sort and then take the first entry in the array to get the item with the latest date.

data.data.sort((a, b) => new Date(b.date) - new Date(a.date))[0];

Upvotes: 3

Related Questions