Reputation: 166
This code removes duplicate li from bottom to top in an unordered list. How can it be modified to remove duplicate li from top to bottom?
function removeDuplicates(){
var map = {};
$("UL").find(".data").each(function() {
var value = $(this);
if (map[value.text()] == null){
map[value.text()] = true;
} else {
$(this).parent('li').remove();
}
});
}
If nothing can be done with the above sample, any other type of efficient code sample answering the question will be appreciated.
Upvotes: 0
Views: 1357
Reputation: 388316
You can try to store the current element and then remove the previous element like
function removeDuplicates() {
var map = {};
$("UL").find(".data").each(function () {
var value = $(this);
if (map[value.text()]) {
map[value.text()].parent('li').remove();
}
map[value.text()] = value;
});
}
Demo:
function removeDuplicates() {
var map = {};
$("UL").find(".data").each(function() {
var value = $(this);
if (map[value.text()]) {
map[value.text()].parent('li').remove();
}
map[value.text()] = value;
});
}
removeDuplicates();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li><span class="data">1</span></li>
<li><span class="data">2</span></li>
<li><span class="data">3</span></li>
<li><span class="data">2</span></li>
<li><span class="data">1</span></li>
<li><span class="data">4</span></li>
<li><span class="data">5</span></li>
<li><span class="data">2</span></li>
</ul>
Upvotes: 2