Skip to content
Advertisement

How to get element of least time in array?

I have an array of of objects:

const sessions = [
{videoStartTime: "2022-08-23T12:05:28.000Z"},
{videoStartTime: "2022-08-23T11:39:51.000Z"},
{videoStartTime: "2022-08-23T10:51:03.000Z"},
{videoStartTime: "2022-08-22T15:49:44.000Z"},
{videoStartTime: "2022-08-22T15:34:42.000Z"},
{videoStartTime: "2022-08-22T15:25:58.000Z"},
{videoStartTime: "2022-08-17T11:11:05.000Z"}
]

And I need to write a function that get an item of the least time in array.

Output shoulde be like this: {videoStartTime: "2022-08-17T11:11:05.000Z"}

Thanks!

Advertisement

Answer

Sorting the whole list for the minimum is very slow; you can use .reduce() instead to linear search:

const sessions = [
  {videoStartTime: "2022-08-23T12:05:28.000Z"},
  {videoStartTime: "2022-08-23T11:39:51.000Z"},
  {videoStartTime: "2022-08-23T10:51:03.000Z"},
  {videoStartTime: "2022-08-22T15:49:44.000Z"},
  {videoStartTime: "2022-08-22T15:34:42.000Z"},
  {videoStartTime: "2022-08-22T15:25:58.000Z"},
  {videoStartTime: "2022-08-17T11:11:05.000Z"}
];

const earliest = sessions.reduce((prev, curr) => {
  if (prev == null)
    return curr;
  
  if (Date.parse(curr.videoStartTime) < Date.parse(prev.videoStartTime))
    return curr;
  else
    return prev;
}, null);

console.log(earliest);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement