1

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?

1
  • Do you get multiple arrays or multiple array items ? There's a difference between the two Commented Feb 22, 2021 at 9:46

2 Answers 2

3

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];
}
Sign up to request clarification or add additional context in comments.

5 Comments

What does the + in +elements.date[i] do? Is that just string to number conversion?
@DBS it converts the string to Number
right it is an unary plus + fo conversion to number.
@NinaScholz why you invoke Set without parenthesis?
@Randall, new operator calls the constructor/function and returns an instance. i need no parameter for an empty set. if you like to chain the instance, you need some braces.
0

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)];;
}

Check this

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.