skip to Main Content

take a blank array and text box. enter any 3 number 1 by 1 in a text box which is automatically store in a blank array 1 by 1 . and not repeat any number in the array. if you enter 4th number in the text box the 1st one will be removed and 4th will be enter.at the end in array only 3 values should be exist not more or less.

how to match the number with the array so that number do not repeat.

2

Answers


  1. Chosen as BEST ANSWER

    var arr=[]
    
            function run(){
                // alert(arr)
                var x=document.getElementById('text').value
    
                if(arr.length < 3){
                    arr.push(x)
                }else
                {
                        arr.shift()
                        arr.push(x)
                }
    
                    document.getElementById('text').value=''
                    document.getElementById('arr').value=arr
                    console.log(arr)
            }
    <input type="text" id="arr" name="">
        <input type="text" id="text" name="">
        <input type="button" onclick="run()" value="add" name="">


  2. If I understood well your question…

    let ar = [];
    
    const inputNb = () => {
      document.querySelector('#inputNumber').addEventListener("keyup", (evt) => {
        evt.stopImmediatePropagation();
        console.log(ar);
        let value = evt.target.value;
        value = value.slice(-1);
        if (!ar.includes(value)) {
          if (ar.length < 3) {
            ar.push(value);
          } else {
            ar.shift();
            console.log(ar);
            ar.push(value);
          }
        }
        console.log(ar);
      });
    };
    window.addEventListener('load', inputNb);
    <br><br>
    <label for="inputNumber">enter number:</label>
    <input type="text" id="inputNumber">
    <br><br>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search