How to find most recent date from an array of object then add new field and return array in react

Viewed 424

I have a array of object in that I want to find most recent date.After getting most recent date then I want to add new field within that object and return the array. I checked it out some stackoverflow question but didn't worked for me,If anyone have any idea please guide me.

e.g:

let myArray = [
               {id: "12ad5e2as", userName: "john", createdAt : 1592638519388}, 
               {id: "52se5e2as", userName: "Herry", createdAt : 1592565371062},
               {id: "25asd5e5e", userName: "Lisa", createdAt : 1592638177825},
               {id: "15ease55e", userName: "Mona", createdAt : 1586505563915}
              ]

after finding most recent date or greater date then I want to add new field and myArray will look like this.

        myArray = [
                   {id: "12ad5e2as", userName: "john", createdAt : 1592638519388}, 
                   {id: "52se5e2as", userName: "Herry", createdAt : 1592565371062},
                   {id: "25asd5e5e", userName: "Lisa", createdAt : 1592638177825,
                    isMostRecent: true},
                   {id: "15ease55e", userName: "Mona", createdAt : 1586505563915}
                  ]

I tried to apply sort function but its adding isMostRecent: true to every object. Can someone please guide me how can I do that?

here is what I have tried.

myArray.sort((a, b) => {
if (a.createdAt > b.createdAt)
    a.isNew = true;
    return -1;
})

Any help will be appreciated.

2 Answers

These dates are Unix Dates and they are compareable. It's straight forward actually smaller numbers are old, bigger numbers are new. Small old, big new.

Just compare two numbers to see which one is most recent (Check for big numbers/dates). You can use Array.sort function here.

myArray.sort(function(a, b){return b.createdAt - a.createdAt});
var newestObject = myArray[0]
newestObject["new_field"] = "New Data"
myArray[0] = newestObject

This will sort biggest to smallest. Notice the createdAt properties in function body.

You can use the sort function

myArray.sort(function(a, b){return b.createdAt - a.createdAt});

without setting the isNew field. And after sort is done you can take the array element with the latest date and add the new field to it.

myArray[0].isNew=true;

Related