Home > Back-end >  Remove duplicate data passed from input field with jQuery
Remove duplicate data passed from input field with jQuery

Time:06-02

I have a input field that accepts numbers. I turn each number to an array on keyup and display them in a div. The issue now is when displaying it displays like this:

1
1
2
1
1
2
3

My code:

$(document).ready(function() {
  // turn input to array
  var inputs = $('#input');
  
  inputs.keyup(function() {
    var input = $('#input').val().split('');
    // remove empty values
    input = input.filter(function(el) {
      return el.length != 0;
    });

    //loop through input array
    for (var i = 0; i < input.length; i  ) {
      // if input is not a number
      if (isNaN(input[i])) {
        // remove the character
        input.splice(i, 1);
      }
      // remove duplicate value in array
      if (input.indexOf(input[i]) != i) {
        input.splice(i, 1);
      }

      // add to a div id
      $('#numbers').append('<h3 >'   input[i]   '</h3>');
    }
  });
});

CodePudding user response:

What I would do is to just "clear" the "#numbers" div before appending. That way you will not have those duplicated (old values).

$('#numbers').html("")

Demo*

$(document).ready(function() {
  // turn input to array
  var inputs = $('#input');
  inputs.keyup(function() {
    var input = $('#input').val().split('');
    // remove empty values
    input = input.filter(function(el) {
      return el.length != 0;
    });

    $('#numbers').html("")
    //loop through input array
    for (var i = 0; i < input.length; i  ) {
      // if input is not a number
      if (isNaN(input[i])) {
        // remove the character
        input.splice(i, 1);
      }
      // remove duplicate value in array
      if (input.indexOf(input[i]) != i) {
        input.splice(i, 1);
      }

      // add to a div id
      $('#numbers').append('<h3 >'   input[i]   '</h3>');
    }

    console.log(input);

  });


});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="input" type="number" />
<div id="numbers"></div>

CodePudding user response:

To resolve this issue, you need to do 3 things:

  • Remove Old Printed Values (in the #number element)
  • Remove Empty Values with a Regex (or by checking for an Empty String)
  • Remove Duplicates from Array with a [...Set(Arr)] operation.

See working example here in CodePen here.

Remove Old Printed Values

Remove old values by calling .html("") or more directly .empty() on #numbers (The former calls the latter, so they do the same thing). Place this call at the beginning of the keyup event handler to erase previously printed content in the #numbers element before proceeding to print new input values.

inputs.keyup(function () {
    $('#numbers').html(""); 
    ... 
} 

Remove Empty Values with a Regex (or by checking for an Empty String)

The regex pattern for empty spaces of any length is /\s / where \s is a space character and means 1 or more space characters. The g flag in the string.replace() method indicates a global search and replace operation. Then call .split() after replacing removing empty spaces.

inputs.keyup(function () {
    $('#numbers').html("");

    var input = $('#input').val(); 

    // remove empty values
    var input = input.replace(/\s /g, "").split(''); 
    ... 
}

Alternatively, you may do it this way:

inputs.keyup(function () {
    $('#numbers').html("");

    var input = $('#input').val().split('');
    // remove empty values
    input = input.filter(function (el) {
        return el !== "";
    }); 
   ...
} 

And not el.length != 0 because each element in the array after the split is at least one character long.

Remove Duplicates from Array with the a [...Set(Arr)] operation

Use the Set() constructor to create a new set from the old array with all duplicates removed then convert the set back to an array with [...Set(Arr)]:

//loop through input array
for (var i = 0; i < input.length; i  ) {
    // if input is not a number
    if (isNaN(input[i])) {
        // remove the character
        input.splice(i, 1);
    }
    // remove duplicate value in array
   input = [...new Set(input)] 
   ... 
 }

Altogether Now

Runnable Code Snippet Below:

$(document).ready(function () { 
  
  // turn input to array
  var inputs = $('#input');
  inputs.keyup(function () {
   $('#numbers').html("");
    
    var input = $('#input').val().split('');  
    console.log(input);
    // remove empty values
    // var input = input.replace(/\s /g, "").split('');  
    input = input.filter(function (el) {
            return el !== "";
        });
   
    //loop through input array
    for (var i = 0; i < input.length; i  ) {
      // if input is not a number
      if (isNaN(input[i])) {
        // remove the character
        input.splice(i, 1);
      }
      // remove duplicate value in array
      input = [...new Set(input)]

      // add to a div id
      $('#numbers').append('<h3 >'   input[i]   '</h3>');
    }

    console.log(input);
  });
});
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <input type="text" id="input">
  <div id="numbers"></div> 
  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
</body>
</html>

  • Related