I am extracting the objects from the array team which have the same year value using the array.filter() function. The only problem it creates twice or n times the arrays depending how many times the same date appears because am looping the array. I want to find a way to bypass already created array with same name and date value.
const team = [{
name: 'John',
date: '2022-01-08T00:00:00.000Z',
team: 'teamA'
},
{
name: 'James',
date: '2021-03-10T00:00:00.000Z',
team: 'teamB'
},
{
name: 'Trevor',
date: '2022-01-08T00:00:00.000Z',
team: 'teamC'
},
{
name: 'Mike',
date: '2021-01-08T00:00:00.000Z',
team: 'teamC'
},
{
name: 'aggelos',
date: '2019-01-08T00:00:00.000Z',
team: 'teamC'
}
];
for (var i = 0; i < team.length; i++) {
d1 = new Date(team[i].date)
let currentDate = d1.getFullYear();
result(currentDate)
}
function result(currentDate) {
const extracted = team.filter(el => new Date(el.date).getFullYear() === currentDate)
console.log(extracted)
}
Output:
{
date: "2022-01-08T00:00:00.000Z",
name: "John",
team: "teamA"
}, {
date: "2022-01-08T00:00:00.000Z",
name: "Trevor",
team: "teamC"
}]
[{
date: "2021-03-10T00:00:00.000Z",
name: "James",
team: "teamB"
}, {
date: "2021-01-08T00:00:00.000Z",
name: "Mike",
team: "teamC"
}]
[{
date: "2022-01-08T00:00:00.000Z",
name: "John",
team: "teamA"
}, {
date: "2022-01-08T00:00:00.000Z",
name: "Trevor",
team: "teamC"
}]
[{
date: "2021-03-10T00:00:00.000Z",
name: "James",
team: "teamB"
}, {
date: "2021-01-08T00:00:00.000Z",
name: "Mike",
team: "teamC"
}]
[{
date: "2019-01-08T00:00:00.000Z",
name: "aggelos",
team: "teamC"
}]