Home > Blockchain >  Delete duplicate Item in Each function
Delete duplicate Item in Each function

Time:10-29

I want to archive that I remove all duplicate items within every each.

So I go a div with items:

<div class="each">
    <div>Test2</div>
    <div>Test</div>
    <div>Test</div>
</div>
<div class="each">
    <div>Test2</div>
    <div>Test</div>
    <div>Test</div>
</div>

And my Jquery so far:

$('.dropPlace').each(function(index){
    console.log($(this).text());
});

So I want to check within every div is there existing two duplicate text. And only removed with the duplicated once within the div.

So the result would be this:

<div class="each">
    <div>Test2</div>
</div>
<div class="each">
    <div>Test2</div>
</div>

CodePudding user response:

here is a working demo.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
    var map = {};
    $("#remove").click(function () {
        // use an object as map
        var map = {};
        $(".dropPlace").each(function () {
            var value = $(this).text();
            if (map[value] == null) {
                map[value] = true;
            } else {
                $(this).remove();
            }
        });
    });
});
</script>
</head>
<body>

<div class="each">
    <div class="dropPlace">Test2</div>
    <div class="dropPlace">Test</div>
    <div class="dropPlace">Test</div>
</div>
<div class="each">
    <div class="dropPlace">Test2</div>
    <div class="dropPlace">Test</div>
    <div class="dropPlace">Test</div>
</div>
<button id="remove">remove</button
</body>
</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The below can be optimized for sure, but it will give the result you asked for:

<div class="each">
    <div>Test2</div>
</div>
<div class="each">
    <div>Test2</div>
</div>

$('.each').each(function() {
  const textAr = [];
  let parent = $(this);
  parent.children('div').each(function() {
    let _this = $(this), elText = _this.text();
    if(textAr.includes(elText)) {  
      parent.children('div').each(function() {
        let _child = $(this);
        if(_child.text() == elText){
          _child.remove();
        }
      })
     }
    else textAr.push(elText)    
  });
});
.each {
  margin-bottom: 1em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="each">
    <div>Test2</div>
    <div>Test</div>
    <div>Test</div>
</div>
<div class="each">
    <div>Test2</div>
    <div>Test</div>
    <div>Test</div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related