jQuery / Method / jQuery.inArray() - Find an Array Index Correctly

jQuery.inArray(value, array, fromIndex) returns the first matching array index, or -1 if no match is found. Test presence with index !== -1. Zero means a match at the first position, so using the return value directly as an if condition can give the wrong answer.

The return value is a position, not a boolean

The jQuery.inArray() API takes the value, array and optional starting index in that order. It is a global jQuery utility called as $.inArray(...) or jQuery.inArray(...), not a DOM-selection method such as $(selector).inArray(...).

Return value Meaning Boolean(index) index !== -1
0 Found at the first entry false true
Integer at least 1 Found at that index true true
-1 Not found in the search range true false

if (index) and index > 0 miss the first entry. JavaScript treats -1 as true in a condition, so simply negating the result is not a fix either. Compare explicitly with -1 or check that the index is at least zero.

Complete example varying type and starting position

Save the entire code as UTF-8 in inarray-demo.html and open it in a browser. Internet is needed for the official jQuery file 4.0.0 from its content delivery network (CDN); no package installation is required. Number/string choices, positive/negative starts, empty arrays and the comparison below were executed with 3.7.1 and 4.0.0.

The array is [0, "0", "alpha", 0]. Value comes from predefined choices, without evaluating string expressions. Only From index is converted through Number() to the starting position.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Search an array with inArray</title>
  <script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
  <style>
    body { font: 16px/1.6 sans-serif; max-width: 760px; margin: 24px auto; padding: 16px; }
    button, select { font: inherit; margin: 4px; }
    pre { white-space: pre-wrap; overflow-wrap: anywhere; }
  </style>
</head>
<body>
  <h1>Find an index rather than a boolean</h1>
  <p>Array: [0, "0", "alpha", 0]</p>
  <label for="value">Value:</label>
  <select id="value"><option value="number">0 (number)</option><option value="string">0 (string)</option><option value="alpha">alpha</option><option value="missing">missing</option></select>
  <label for="from">From index:</label>
  <select id="from"><option>0</option><option>1</option><option>3</option><option>9</option><option>-1</option></select>
  <button type="button" id="search">Search</button>
  <button type="button" id="reset">Reset</button>
  <pre id="result" aria-live="polite"></pre>
  <script>
    $(function () {
      const array = [0, "0", "alpha", 0];
      const choices = { number: 0, string: "0", alpha: "alpha", missing: "missing" };
      function search() {
        const value = choices[$("#value").val()];
        const fromIndex = Number($("#from").val());
        const index = $.inArray(value, array, fromIndex);
        const found = index !== -1;
        $("#result").text(`value=${JSON.stringify(value)} (${typeof value})\nindex=${index}\nfound=${found}\nBoolean(index)=${Boolean(index)}`);
      }
      $("#value, #from").on("change", search);
      $("#search").on("click", search);
      $("#reset").on("click", function () {
        $("#value").val("number");
        $("#from").val("0");
        search();
      });
      search();
    });
  </script>
</body>
</html>

Initially, numeric zero is found at the first position:

value=0 (number)
index=0
found=true
Boolean(index)=false
  1. Choose 0 (string). Its index is 1: numeric 0 and string "0" differ.
  2. Return to 0 (number) and choose From index 1. The result is 3, skipping the earlier numeric zero.
  3. A start of 3 still returns 3 because the starting position is included.
  4. 9 exceeds array length: index is -1 and found false, while Boolean(index) remains true.
  5. -1 starts at index 3, one position from the end, finding numeric zero.
  6. With start 0, alpha and missing give 2 and -1. Reset restores numeric zero and start zero; Search repeats the current conditions.

Strict comparisons and fromIndex bounds

Comparison is strict, like ===. String "0" is not converted to numeric 0, and partial strings are not matched. Decide whether input values should be strings or numbers and define accepted conversions and failure handling explicitly.

Omitting the start uses zero. A negative start is calculated relative to the end, but the search still proceeds forward. A start far before the array uses zero; a start at or beyond length returns -1. The result is an absolute array index, not a position relative to the start. Duplicates still produce only the first match at or after that start.

Objects are compared by reference, not by equal-looking properties. Run this complete fragment in the developer tools Console to compare the same object with a new one, NaN and native alternatives.

const item = { id: 1 };
console.log(`same object=${$.inArray(item, [item])}`);
console.log(`new object=${$.inArray({ id: 1 }, [item])}`);
console.log(`NaN index=${$.inArray(NaN, [NaN])} | includes=${[NaN].includes(NaN)}`);
console.log(`empty=${$.inArray("a", [])}`);
const array = ["a", "b", "a"];
console.log(`start 1=${$.inArray("a", array, 1)} | start -1=${$.inArray("a", array, -1)}`);
console.log(`native index=${array.indexOf("a", 1)} | native found=${array.includes("a", 1)}`);
same object=0
new object=-1
NaN index=-1 | includes=true
empty=-1
start 1=2 | start -1=2
native index=2 | native found=true

Choose indexOf or includes and guard later operations

For a normal array, native array.indexOf(value, fromIndex) also returns a position. A project without jQuery does not need it just for one array search. Note the call style: array.indexOf(value) rather than $.inArray(value, array).

For presence alone, array.includes(value, fromIndex) returns true or false directly. Its comparison is not completely identical: NaN gives -1 with $.inArray() or indexOf(), but true with includes(). Object identity and number/string distinctions still matter.

Check for -1 before using a result to remove an entry. Passing a missing result directly to splice() can remove the final entry. For unexpected results, inspect types, argument order, start position, object identity and whether the original array has changed.