Khairul Habib
Khairul Habib

Reputation: 131

filter an API data with current date in javascript

this is example of data from my API look like.

const data = [{
    "id": "1",
    "name": "Lesley",
    "creationDate": "2019-11-21 20:33:49.04",
},
{
    "id": "2",
    "name": "Claude",
    "creationDate": "2019-11-21 20:33:09.397",
},
{
    "id": "3",
    "name": "Lesley",
    "creationDate": "2019-11-20 20:31:46.357",
{
    "id": "4",
    "name": "Yin Sun Shin",
    "creationDate": "2019-11-20 23:13:40.41",
},
{
    "id": "5",
    "name": "Claude",
    "creationDate": "2019-11-21 23:13:30.18",
},
{
    "id": "6",
    "name": "Moskov",
    "creationDate": "2019-11-20 23:10:22.863",
},
{
    "id": "7",
    "name": "Lesley",
    "creationDate": "2019-11-19 01:15:26.457",
},
{
    "id": "8",
    "name": "Yin Sun Shin",
    "creationDate": "2019-11-19 19:39:32.233",
},
{
    "id": "9",
    "name": "Claude",
    "creationDate": "2019-11-18 19:38:54.117",
}]

i have a list of data that need to display all information in vue-ant-design list. but there is too much of data that make the system lagging. i'm intended filter this data before being displayed. i've tried some other javascript function to display the latest date data but not succeed. is there any javascript reference that i can refer or any sharing that i can refer for how to filter this API data with the latest date in the creationDate? i've no more idea on how to filter this data.

Upvotes: 2

Views: 808

Answers (1)

Yosvel Quintero
Yosvel Quintero

Reputation: 19070

The best will be to get the data from the API ready to show..

But, with JavaScript in the frontend you can do:

  1. Sort by creationDate DESC
  2. Filter elements with creationDate.substring(0, 10) equal to first element's creationDate.substring(0, 10) in the sorted array

Code:

const data = [{ "id": "1", "name": "Lesley", "creationDate": "2019-11-21 20:33:49.04", }, { "id": "2", "name": "Claude", "creationDate": "2019-11-21 20:33:09.397", }, { "id": "3", "name": "Lesley", "creationDate": "2019-11-20 20:31:46.357", }, { "id": "4", "name": "Yin Sun Shin", "creationDate": "2019-11-20 23:13:40.41", }, { "id": "5", "name": "Claude", "creationDate": "2019-11-21 23:13:30.18", }, { "id": "6", "name": "Moskov", "creationDate": "2019-11-20 23:10:22.863", }, { "id": "7", "name": "Lesley", "creationDate": "2019-11-19 01:15:26.457", }, { "id": "8", "name": "Yin Sun Shin", "creationDate": "2019-11-19 19:39:32.233", }, { "id": "9", "name": "Claude", "creationDate": "2019-11-18 19:38:54.117", }]
const result = data
  .sort((a, b) => new Date(b.creationDate) - new Date(a.creationDate))
  .filter((a, _, arr) => a.creationDate.substring(0, 10) === arr[0].creationDate.substring(0, 10))

console.log(result)

Upvotes: 1

Related Questions