Reputation: 120
I have a for loop that goes through all elements of a certain class and returns the value (which in my case it's a date — e.g. 2020-05-15) and splits it. So I get multiple arrays from which I want to create one joined array of all years without duplicates.
My code is basic right now, but I'm constantly running into troubles.
function getDate () {
for (var i = 0; i < total; i++) {
var dateSplit = elements.date[i].innerText.split('-');
// this returns multiple arrays of {'year', 'month', 'day'}
var dateOnly = dateSplit[0] // returns multiple strings of years
}
}
How do i join dateOnly into one array?
Upvotes: 1
Views: 68
Reputation: 2834
Try the below
function getYearAsArray(p1, p2) {
var temp = ['2025-05-15', '2092-05-15', '2021-05-15', '2021-05-15'];
var result = temp.map(i=> {
return i.replace(/^(\d{4})(-\d{2}-\d{2})$/, '$1');
});
return [...new Set(result)];;
}
Upvotes: 0
Reputation: 386600
You could collect the years in a Set
and return an array of unique values.
function getDate() {
const years = new Set;
for (var i = 0; i < total; i++) {
years.add(+elements.date[i].innerText.split('-', 1)[0]);
}
return [...years];
}
Upvotes: 3