0

I have list of object from my api, I want to display the latest value,

Here's my object. enter image description here

Here's how I got my location 3.

records.forEach((record) => {
      if (record.location == locationId) {
        result.push(record);
  }});

But now I want to get the latest record from it.

Any help would be very thankful!

Community
  • 1
  • 1
w0nght
  • 33
  • 5

4 Answers4

2

Sorting is a relatively expensive operation (O(n log n) time complexity).

Instead, you may traverse your source array with Array.prototype.reduce() just once (O(n) time algorithm) to find out the latest record that corresponds to desired location:

const src = Array.from(
  {length: 15},
  (_,i) => ({location: 0|i/3, timestamp: new Date(2020,5,i+1).toLocaleString('uk-UA')})
),

      getLatestForLocation = (log, locationId) =>
        log.reduce((r, item) => {
          if(locationId != item.location) return r
          if(!r.timestamp || r.timestamp < item.timestamp)
            r = item
          return r
        }, {})

console.log(src)
console.log(`latest record for location id 2: `, getLatestForLocation(src,2))
.as-console-wrapper{min-height:100%;}
Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42
0

You filter then sort then take the first element:

var records = [
  {value: '1', location: '3', timestamp: '2020-04-28 10:12'},
  {value: '2', location: '2', timestamp: '2020-04-28 00:24'},
  {value: '3', location: '3', timestamp: '2020-04-28 07:37'},
  {value: '4', location: '3', timestamp: '2020-04-28 14:27'},
  {value: '5', location: '3', timestamp: '2020-04-28 23:28'},
  {value: '6', location: '1', timestamp: '2020-04-28 10:13'}
]

console.log(records.filter(x => x.location == 3).sort((a,b)=> a.timestamp < b.timestamp ? 1 : -1)[0])
djcaesar9114
  • 1,880
  • 1
  • 21
  • 41
0

Sort the records:

records.sort(({ timestamp: a }, { timestamp: b }) => a > b ? -1 : 1);

Now records[0] is the latest one.

GirkovArpa
  • 4,427
  • 4
  • 14
  • 43
  • 1
    The "location" filter is not taken into account and you lose in efficiency because of the Date. Seeing the format, you can just sort alphabetically ;) – djcaesar9114 Jun 11 '20 at 20:57
  • 1
    Technically I don't think you need to convert to a Date object, since ISO format dates are alphabetically comparable. – antun Jun 11 '20 at 20:58
0

Your routine will create a result array that looks something like this:

const result = [                                         
  { value: '15', location: '3', timestamp: '2020-06-11 19:48:28' },
  { value: '16', location: '3', timestamp: '2020-06-10 19:48:28' },
  { value: '14', location: '3', timestamp: '2020-06-19 19:48:28' } 
];

Then you can simply do:

const latest = result.sort((a,b) => a.timestamp < b.timestamp)[0];
antun
  • 2,038
  • 2
  • 22
  • 34