Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Rachel Heneault
PLUS
Rachel Heneault
Courses Plus Student 12,155 Points

Javascript for loops on data

After doing a rest api call, I have a list of data with 42 items. Each one has a date. Some dates are the same. I want to create a drop down based on the dates. But if I do this it shows all the dates. How do write the loop that will group the dates together and only show the a single date for each instance?

for (var i = 0;i < dat.length;i++){
    html+='<option 
        value='+dat[i].highlight+'>'+dat[i].highlight+'</option>';
}

MOD: I just added a bit of formatting to the code so people can follow it more easily and be better able to help. You can find out how to do this in the Markdown Cheatsheet below the textbox when writing a question or answer. Don't worry, it's easy! :-)

2 Answers

Steven Parker
Steven Parker
229,785 Points

It looks like you only need unique dates, and don't need to maintain a correspondence with the original object(s). If so, you may be able to convert the dates to timestamps, pass them through a Set object (to insure uniqueness), and then convert them back. I haven't tried it, but I'm thinking it might look like this:

var uniqueDates = Array.from(new Set(dat.map(d => d.highlight.getTime())))
                       .map(t => new Date(t));
for (var d of uniqueDates) {
    html += `<option value="${d}">${d}</option>`;
}

If you do need to maintain a correspondence, you'd probably need to create some extra processes, including a custom object comparison function.

Rachel Heneault
PLUS
Rachel Heneault
Courses Plus Student 12,155 Points

Thank you for your help.

When will the day exist when I don't get stumped or frustrated....

Steven Parker
Steven Parker
229,785 Points

If you never get stumped, it's time to find more challenging work! Tasks you can accomplish easily don't give you a chance to grow and will eventually become boring.

And there are always resources you can turn to. Sometimes perusing the documentation will do, otherwise you can seek advice from a co-worker, supervisor, or a forum like this one.

Enjoy working out the "puzzles", and happy coding!