-4

So say I have some colors:

Red

Blue

Blue

Green

I want to put only the unique ones into an array. Then, I want each item in that array to be added to a list of colors that already exists. So my final result would be something like:

<ul>
   <li>Original Color</li>
   <li>Original Color</li>
   <li>Red</li>
   <li>Blue</li>
   <li>Green</li>
</ul>

I got as far as putting the colors into an array, and then finding the unique ones. But I am lost from there.

Okay, here is what I have so far:

var yearArray = [];
$('#calendar .item').each(function(){
   var dataYear = $(this).attr('data-year');
   yearArray.push(dataYear);
});
yearArray = $.unique(yearArray);

I was afraid to post that because I don't know if it makes any sense, especially with my example. I'm really getting a list of years and need to put only 1 of each year into a ul, in order to paginate a calendar. I have my unique list of years, but I dont know what to do with it now.

Shonna
  • 993
  • 2
  • 9
  • 12
  • If you're asking a problem about javascript, it would help to include the code you've tried. – zzzzBov May 12 '14 at 21:04
  • So...you're really asking "how to add HTML list items with JavaScript/jQuery"? Try [this question](http://stackoverflow.com/questions/1145208/jquery-how-to-add-li-in-an-existing-ul). – Zhihao May 12 '14 at 21:06
  • [This](http://stackoverflow.com/questions/1960473/unique-values-in-an-array) question has a really good example of how to add a function to `Array.prototype` to pull unique values. – War10ck May 12 '14 at 21:10
  • Basically I need Zhihao and War10ck's links combined into 1. I can do the individual things. I don't know how to make them work together. – Shonna May 12 '14 at 21:18
  • You seem to already have the unique part down, as mentioned in your question, so you don't need @War10ck's link. You only need to copy-paste the top answer in the link from my previous comment, then replace their list item content with yours. You don't need to combine anything because these are separate issues, and you only need to put the "add list item code" directly after "get unique items" code. What part are you having trouble with? – Zhihao May 12 '14 at 21:46
  • The top answer you are referring to, I don't know how to replace their li with my array. $("#header ul").append('
  • '+yearArray+`
  • `); is what I imagine but that's not right. – Shonna May 12 '14 at 21:58
  • Looks like you found something that works. To answer your question though, it would be something like `$("#years ul").append('
  • '+year+'
  • ')`, where `year` is an item from your `yearArray`. That you can access an item from your array with `yearArray[indexNumber]`, and do this in a `for` loop. I would recommend brushing up on some more JavaScript, and jQuery selector basics before trying to manipulate the DOM. Best to learn how to crawl before trying to walk or run. :) – Zhihao May 12 '14 at 23:23