Why is lodash returning -1 here? It's clearly in there?
Ignores = ['load', 'test', 'ok'];
alert(_.findIndex(Ignores, 'ok') );
findIndex - Returns the index of the first element in the array where predicate is true, and -1 otherwise. indexOf - Returns the index of the first occurrence of a value in an array.
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.
get() method in Lodash retrieves the object's value at a specific path. If the value is not present at the object's specific path, it will be resolved as undefined . This method will return the default value if specified in such a case.
That's because findIndex() takes as parameters an array and a predicate, a function that returns a boolean value based on some condition.
Assuming you are searching for needle
in haystack
, you can achieve what you want with normal JavaScript:
alert(haystack.indexOf(needle));
You can use _.indexOf
(from @Juhana):
alert(_.indexOf(haystack, needle))
You can do it with _.findIndex
too:
alert(_.findIndex(haystack, function(x) { return x === needle; }));
or:
alert(_.findIndex(haystack, _(needle).isEqual));
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