Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

jQuery remove duplicate but keep last occurance

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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/

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading