I have a few divs that I'd like to put into an array.
When I try to use jQuery.inArray(), my div (as a jQuery object) isn't found. Why not?
var myArray = [ $("#div1"), $("#div2"), $("#div3") ];
alert(jQuery.inArray($("#div1"),myArray)); // returns -1
To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.
The findIndex() method takes a function as the first parameter. This function is executed on every element of the array and the element for which the function returns “true” is the one that matched the specified condition. Thus the index of this matched element is stored in the index variable.
TypeScript - Array indexOf() indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
JavaScript Array findIndex() The findIndex() method executes a function for each array element. The findIndex() method returns the index (position) of the first element that passes a test. The findIndex() method returns -1 if no match is found.
$
creates a new jQuery collection object each time, so var a = $("div"), b = $("div")
will actually be two different objects that don't equal each other.
Instead you can just use the selectors or some other identifying feature of the element.
var myArray = ["#div1", "#div2", "#div3"];
However it really depends on your use case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With