Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash findIndex not working

Why is lodash returning -1 here? It's clearly in there?

Ignores = ['load', 'test', 'ok'];
alert(_.findIndex(Ignores, 'ok') );
like image 973
yeouuu Avatar asked Aug 21 '15 09:08

yeouuu


People also ask

What is the difference between findIndex and indexOf in JavaScript?

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.

How do you find the index of an object 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.

How does Lodash get work?

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.


1 Answers

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));
like image 56
tgkokk Avatar answered Sep 28 '22 20:09

tgkokk