SO is full of these questions, I know, but after going through 20 pages and numerous google searches I end up asking because I can't find the answer.
I want to filter through data attributes and keep the last occurrence. So for instance with this code:
<div data-id="001">Hello</div>
<div data-id="001">World</div>
<div data-id="002">Keep</div>
<div data-id="002">Only</div>
<div data-id="002">Unique</div>
<div data-id="003">Last</div>
<div data-id="003">Word</div>
<div data-id="004">Please</div>
<br><br>
<p>Result should be: World Unique Word Please</p>
I tried numerous ideas from the SO pages and google searches but I have no luck in keeping the last items. First items though work perfectly with this code.
var found = {};
$('[data-id]').each(function(){
var $this = $(this);
if(found[$this.data('id')]){
$this.remove();
}
else{
found[$this.data('id')] = true;
}
});
Here is a fiddle, hopefully that makes things easier http://jsfiddle.net/hx9Lzqf6/
CodePudding user response:
We can find the last index with same id,store them into an array,then call $.each()
again to remove elements with index not in the array
let result = {}
$('[data-id]').each(function(i,e){
let id = $(e).attr("data-id")
result[id] = i
});
result = Object.values(result)
$('[data-id]').each(function(i,e){
let id = $(e).attr("data-id")
if(!result.includes(i)){
$(e).remove()
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-id="001">Hello</div>
<div data-id="001">World</div>
<div data-id="002">Keep</div>
<div data-id="002">Only</div>
<div data-id="002">Unique</div>
<div data-id="003">Last</div>
<div data-id="003">Word</div>
<div data-id="004">Please</div>
<br><br>
<p>Result should be: World Unique Word Please</p>