0

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 class="H3-em9z5i-0 CodeField__InputCode-sc-1270tiq-1 huhlDl cpSCaJ">' + input[i] + '</h3>');
    }
  });
});
6
  • 1
    I'd use a Set instead of an array. Sets contain unique values. Commented Jun 1, 2022 at 13:23
  • if (input.indexOf(input[i]) != i) { input.splice(i, 1); } above code is wrong, try with following if (input.indexOf(input[i]) != -1) { input.splice(i, 1); } or input = input.filter(function(element,index,self){ return index === self.indexOf(element); }); Commented Jun 1, 2022 at 13:25
  • @pramodkadam seemed it work but it return undefined, i dont want to prevent user from putting in same number just that the output returns new array instead of appending Commented Jun 1, 2022 at 13:35
  • like this ["1"] ["1", "2"] Commented Jun 1, 2022 at 13:35
  • @PreciousOladele do you want output like the above? then your logic is wrong. Commented Jun 1, 2022 at 13:43

2 Answers 2

1

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 class="H3-em9z5i-0 CodeField__InputCode-sc-1270tiq-1 huhlDl cpSCaJ">' + 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>

Sign up to request clarification or add additional context in comments.

Comments

0

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 class="H3-em9z5i-0 CodeField__InputCode-sc-1270tiq-1 huhlDl cpSCaJ">' + 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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.