0

I have my project which is almost complete. But the problem is a small bug in my drop down box with is dynamic, which means whenever a new expense is added to the list, the corresponding year gets added to the options tag within select tag in FilterExpense.jsx file. The issue goes like even if a particular year is present in the drop down list, the same year gets added again and again all the time when an expense of the same year is added to the list.

Here is the picture showing two 2021 while the program is expected to show it only once. How to fix this bug?

enter image description here

THANKS IN ADVANCE!!!

1
  • You've not included the relevant code in your question, and the link to project is now broken. Commented Jul 27, 2023 at 15:39

1 Answer 1

3

You can eliminate duplicates inside your addYear function by using a Set. The following example will gather all of the four-digit years, use a Set to eliminate duplicates, and then spread that set into an array and create options.

function addYear() {
  const items = sendYear.map((preValue) =>
    new Date(preValue.date).getFullYear()
  );

  return [...new Set(items)].map((year) => {
    return (
      <option key={year} value={year}>
        {year}
      </option>
    );
  });
}

I also wanted to note for you that the .getFullYear() method might yield unexpected results. For example, new Date('2021-01-01').getFullYear(); for me (in Eastern Daylight Time) actually returns 2020. Instead, since your date format is consistently YYYY-MM-DD, you could consider getting the year by doing preValue.date.split('-')[0].

Sign up to request clarification or add additional context in comments.

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.