-1

I need to sort an array by the nearest timestamp to the current one, but the sorting is wrong. How can this be done?

console.log(new Date(1627569000000));
console.log(new Date(1627565400000));
console.log(new Date(1627561800000));
console.log(new Date(1627572600000));


const arr = [{
  from: 1627569000000
}, {
  from: 1627565400000
}, {
  from: 1627561800000
}, {
  from: 1627572600000
}];

const now = 1627557449263;


const [res] = arr.sort(item => item.from - now);


console.log(new Date(res.from))
mplungjan
  • 169,008
  • 28
  • 173
  • 236
lecham
  • 2,294
  • 6
  • 22
  • 41
  • Is your goal to sort the whole array, or only to get the nearest one? If you want to sort the full array, why only log the first entry? – A_A Jul 29 '21 at 11:44
  • your question is not that clear what do you mean by sort nearest timestamp to the current one ? are you intended to get nearest one date? – Ravikumar Jul 29 '21 at 11:44

3 Answers3

0

This might help you out

const arrayOfTimestampObjects = [
  { from: 1627569000000 },
  { from: 1627565400000 },
  { from: 1627561800000 },
  { from: 1627572600000 },
]
// The below gives [1627569000000, 1627565400000, ...]
const timestamps = arrayOfTimestampObjects.map((obj) => obj.from)

// [9733353, 6133353, 2533353, 13333353]
const differenceFromCurrentTime = timestamps.map((d) =>
  Math.abs(new Date() - new Date(d).getTime()),
)
// 2
const indexOfClosest = differenceFromCurrentTime.indexOf(
  Math.min(...differenceFromCurrentTime),
)
console.log(timestamps[indexOfClosest])
// 1627561800000 is the closest to the current time
omeanwell
  • 1,847
  • 1
  • 10
  • 16
0

This sort function will return the values in the order of how close they are to now:

const res = arr.sort((a,b) => {
  if (Math.abs(now - a.from) > Math.abs(now - b.from)) {
    return 1
  }
  if (Math.abs(now - b.from) > Math.abs(now - a.from)) {
    return -1
  }
  return 0
} );
Copper
  • 35
  • 7
0

the function taken by Array.sort should be a compareFunction (it compare elements in the array), not keySelector.


You can first extract the key, sort by key, then get back the array.

const arr = [{from: 690}, {from: 654}, {from: 618}, {from:260}];

const now = 574.49263;

function OrderBy(arr,keySelector){
  return arr.map(x=>[x,keySelector(x)]) // pair of (element, key)
     .sort((x,y)=>x[1]-y[1]) // order by key
     .map(x=>x[0])  // select element
}
const res = OrderBy(arr,item => Math.abs(item.from - now)); // abs for distance

console.log(res)
apple apple
  • 10,292
  • 2
  • 16
  • 36