I am trying to return an array with objects that have the nearest date.
I have something like this:
let arr = [
{
"name": "test1",
"date": "2022-05-01T00:00:00.000 00:00"
},
{
"name": "test2",
"date": "2022-05-01T00:00:00.000 00:00"
},
{
"name": "test3",
"date": "2022-04-01T00:00:00.000 00:00"
},
{
"name": "test4",
"date": "2022-03-01T00:00:00.000 00:00"
},
]
I need to return an array with the objects with the nearest date, something like this:
let arrNewDates = [
{
"name": "test1",
"date": "2022-05-01T00:00:00.000 00:00"
},
{
"name": "test2",
"date": "2022-05-01T00:00:00.000 00:00"
},
]
Because they are the objectst with the nearest date to the current date.
I've been thinking in ways to solve this problem, but no success. Does anyone know a function that can solve that?
Thanks,
CodePudding user response:
You can use a filter
go through the entire array and only keep elements that are at span
distance. Something similar to this:
const closestDates = (input: Record<string, string>[], span: number) => {
return input.filter(item => Math.abs(new Date(item.date) - new Date()) <= span) )
}
And then you can use it like this:
closestDate(arr, 1000)
Note:
- I'm using
Record<string, string>
, but you should use a narrower type span
is measured in milliseconds
CodePudding user response:
First we need a helper function getDateDifference
to get the actual date difference of two items, similarly to @Radu Diță.
The next step would be to iterate in a double for loop over the whole array to compare each dateDifference
and each time we get a smaller one we save that result in an array.
The complexity would be O(n²) since we have to compare each item with each other.
const arr = [{
name: "test1",
date: "2022-05-01T00:00:00.000 00:00",
},
{
name: "test2",
date: "2022-05-01T00:00:00.000 00:00",
},
{
name: "test3",
date: "2022-04-01T00:00:00.000 00:00",
},
{
name: "test4",
date: "2022-03-01T00:00:00.000 00:00",
},
];
const getDateDifference = (item1, item2) => {
return Math.abs(new Date(item1.date) - new Date(item2.date));
};
let closestDistance = undefined;
let arrNewDates = [];
arr.forEach((item1) => {
arr.forEach((item2) => {
if (item1 !== item2) {
const dateDifference = getDateDifference(item1, item2);
if (closestDistance === undefined || dateDifference < closestDistance) {
closestDistance = dateDifference;
arrNewDates = [item1, item2];
}
}
});
});
console.log(arrNewDates);