Find number closest to other number in objects in array

Hi there!
I have an array filled with objects like this:

[{"timestamp": "1593099412", "pingtime": "1.054"}, {"timestamp": "1593099413", "pingtime": "1.055"}]

and I want to find the closet timestamp to a new timestamp I make. Is this possible? If so, how? I think I can get the timestamps via

console.log(data[0].timestamp);

but I want to check them all and then get the closest one. Any ideas?
Any help appreciated in advance :slight_smile:
Eddie

Check this out @EddiesTech


Array.sort @MDN

Yes, thanks for this. Only problem is that the array has objects inside. Any ideas?

An easiest way I think of, is to do this:

var arrayWithObjects = [{time: 82373}, {time: 8234738}];
var arrayWithTime = [];
for (var i = 0; i < arrayWithObjects.length; i++) {arrayWithTime.push(arrayWithObjects[i].time);}
// sort out arrayWithTime

There is better way to do this, but this is the easiest way I found in short amount of time.

1 Like

In your case, it’s a.timeStamp instead of a. So, third line would be like,

ObjectsArray.sort(
    (first, second) =>
    Math.abs(+first.ts - newTs) - Math.abs(+second.ts - newTs)
)
1 Like

Will try when I get back home. Thanks for the help! :slight_smile:

Here’s the full solution:

    var arrayWithObjects = [{time: 82373}, {time: 8234738}];
var arrayWithTime = [];
    var newTs = "8234739";
for (var i = 0; i < arrayWithObjects.length; i++) {arrayWithTime.push(arrayWithObjects[i].time);}
    const closest = arrayWithTime.reduce((a, b) => {
    return Math.abs(b - newTs) < Math.abs(a - newTs) ? b : a;
});
    console.log(closest);
1 Like

Just in case :stuck_out_tongue:
You don’t need to sort the whole database, you just have to get a first closest entry. Therefore, you need to search through the array and stop on a first match:

const ts = '1234567890'
const getClosestByTS = d => d.find(e => e.timestamp*1 - ts*1 > 0)  // or >= 0 if you want to get result with equal ts

Nice, how you’d used reduce variation. :ok_hand:
But, in case you need to fetch the whole object, you can try sort in a similar fashion.