I have big array of objects
let objectsList = [
{name: 'Misha', surname: 'Borovuk', id: '1', createdProfile: '11/02/2022'}
{name: 'Karina', surname: 'Burba', id: '2', createdProfile: '17/01/2022'}
{name: 'Alina', surname: 'Shulan', id: '3', createdProfile: '05/01/2021'}
{name: 'Sasha', surname: 'Uena', id: '4', createdProfile: '11/02/2021'}
{name: 'Stepan', surname: 'German', id: '4', createdProfile: '08/02/2022'}
]
And 2 dates let fromDate = '24/12/2021'; let toDate = '11/02/2022';
And i need to remove those objects which are not in range, and group those objects which are in range by weeks.
For instance result should look like this :
let result = [
[
{name: 'Karina', surname: 'Burba', id: '2', createdProfile: '17/01.2022'}
],
[
{name: 'Stepan', surname: 'German', id: '4', createdProfile: '08/02/2022'},
{name: 'Misha', surname: 'Borovuk', id: '1', createdProfile: '11/02/2022'},
// Because they addad on same weak
],
]
let dates = [
[
'17/01/2022',
'23/01/2022'
],
[
'07/02/2022',
'13/02/2022'
],
]
But does anyone know is it possible to do without for loops, maybe with groupBy
of forEach
, map
?
In order to not complicade application?
I was looking a lot and only found a few examples with lodash
and groupBy
groupBy(objectsList, (dt) => moment(dt).week());
But they all use only one from fromDate
parameter and don't use toDate
parameter.
And also this aproach doenst allow to get rid of those items which are not in range.
Sorry for not providing any code solutions, all my ideas have lots' of nested loops and conditions
CodePudding user response:
You need to cast your string-dates into actual JavaScript Date-Objects
with new Date('01/12/2022')
. After all of your dates are actual Date-Objects
, you can compare them with operators: new Date('01/12/2022') < new Date('02/12/2022') // true
. After that, you need to loop over them and split them correctly. As this is more of a math-thing, you would benefit most, if you try to solve this with regular JS methods like map
or foreach
. This is a fairly easy task and good practice for yourself.
CodePudding user response:
But does anyone know is it possible to do without for loops, maybe with groupBy of forEach, map?
You are probably looking for the filter
method. It will return each item that passes a conditional test in its callback, the conditional test in your case being a date within two dates.
Try something like
const results = objectsLists.filter(item => {
return item.createdProfile.getTime() >= fromDate.getTime() &&
item.createdProfile.getTime() <= toDate.getTime()
})
I don't recognize your date format and am not sure it will play nicely with JavaScript's built-in Date class. If possible, you should consider using that instead. If not, you could still use the filter method with a more convoluted conditional checking month/day/year positions in the createdProfile
string.