Reputation: 1523
I am populating an li
list with an ajax call. I have duplicate values in the table that I do not want in the li
. Only unique values should be added to the li
list. I know this should be addressed on the SQL side but for now I just need to be able to filter the list in jQuery.
HTML:
<ul id="bookList">
</ul>
JS:
$.ajax({
type: "GET",
url: "getchapters.php",
dataType: 'json',
cache: false,
success: function(results) {
$.each(results, function(index, result) {
var Books = result.books.split(",");
$("#bookList").append('<li>' + Books + '</li>');
});
}
});
So if "Green eggs and Ham" book appears once, it is added to the list. The second time it appears it will be ignored.
Upvotes: 0
Views: 2273
Reputation: 1183
after this
var Books = result.books.split(",");
use this
Books = Books.reduce(function(c,l){
if(c.indexOf(l) > -1){
return c;
}
c.push(l);
return c;
},[]);
now books has only unique items
** update : ** you can use sets
booksSet = new Set(Books);
now you have booksSet ,, you can use forEach on it or whatever you want ,,
Upvotes: 0
Reputation: 616
You can create a separate array outside of the loop to track
var unique = [],
books;
$.each(results, function(index, result) {
books = result.books.split(",");
if($.inArray(books, unique) === -1) {
unique.push(books);
$("#bookList").append('<li>' + books + '</li>');
}
}
Upvotes: 3
Reputation: 2871
Use this code to remove duplicated from array before populating the list:
var Books = result.books.split(",");
var uniqueNames = [];
$.each(Books, function(i, el){
if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
});
Upvotes: 0