1

I am using an input field to put user inputs in an array.

I want to check if the user inputted number is already in the array or not. And if it is in the array then the input should not be re-added.

Here is my attempt.

if(e.keyCode === 43){

    var num = document.getElementById("numbers").value;
    var oks = [];

    // set num


    // check if num is in the oks array

    if( oks[num]==num ){

        alert("It is already there."); 

    }
    else{

        oks[num.value]=num.value;

    }

    console.log(oks.value);


}

With the above code it says undefined in the console log.

Please help me find where I am wrong in this.

Thanks a lot :)

2 Answers 2

3

Your code has lots of mistakes, such as :

var oks = [];

The above is saying that every time the user inputs something, the array is empty, therefore there is nothing there, therefore the value is not there, so there is no use of trying to know whether the value exists or not, because it doesn't, so you should declare the oks variable outside of the eventListener.

oks[num]

The above is not the value, it's the element in the array whose index is the value, which are very different.

num.value

The above is a syntax error, because the num variable is a number not a dom element that has a value attribute.

And here's the solution to your problem :

if( oks.indexOf(num)>-1 ){
    alert("It is already there.");
}
else{
    oks.push(num);
}
Sign up to request clarification or add additional context in comments.

Comments

1

you can do

if(oks.indexOf(num) != -1) 

to check whether it lies in the array or not or alternatively you could use oks as an object and check if a fiels of a similar value is defined or not, which should be more efficient

var oks = [];

is being initialised on every request, hence it is always empty, initialise it at a parent/global scope, you should use

var oks = {};
// at a parent scope

if(e.keyCode === 43){

    var num = document.getElementById("numbers").value;
    // set num


    // check if num is in the oks array

    if( oks{num} != undefined ){

        alert("It is already there."); 

    }
    else{

        oks[num]=true;

    }

    console.log(oks.num);


}

4 Comments

thanks @marvel308, but still it is not working... it keeps adding... and it doesn't alert :(
make var oks = []; global
since oks is initialised everytime it is always empty
thanks a lot, @marvel308, this worked like a charm mashaAllah :)

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.