Search code examples
javascriptarrayslaravelindexof

how to check whether a value exists in array in javascript?


I have an array in my laravel blade file and am accessing it as below inside javascript:

var test = {!! json_encode($test) !!};

When I print the test variable in the console, it prints the variable as below:

variable test console print

I have one form input value accessed as below:

$("#add-employeeId").val()

When I print this value in the console, it prints the value as below:

form input

Now I need to check whether the form input exists in the test variable, am doing it as below:

function isInArray(array, search)
    {
        return array.indexOf(search) >= 0;
    }

//check
isInArray(test, $("#add-employeeId").val())

But this always returns false, even the value exists. I need to know what's wrong with my check and what am missing. Thank you.


Solution

  • indexOf() compares searchElement to elements of the Array using strict equality (the same method used by the === or triple-equals operator).

    $("#add-employeeId").val() is returning string value and you are comparing it to int values.

    Your function should be:

    function isInArray(array, search)
    {
        return array.indexOf(parseInt(search)) >= 0;
    }