zoqaweek.blogg.se

Javascript array findindex
Javascript array findindex












javascript array findindex

When using indexOf it will look through each array item and return the first index it finds that matches the value we provided to it, if it does not find anything it will return -1. If the callback returns false it will move onto the next array item.īoth methods will return -1 if they cannot find the correct index before the end of the array. If the callback function returns true, the findIndex method will consider the array item to match what we are looking for and it will return that index. The callback function we provide to findIndex always needs to return a boolean value. findIndex ( arrayItem => arrayItem = "d" ) // -1Īs you can see both are very similar and give you the same result when looking for the same value. findIndex ( arrayItem => arrayItem = "b" ) // 1ĮxampleArray. Here is a visual example of the differences between method vs the method:ĮxampleArray. What this means is that indexOf will only ever look for a value in an array, whereas findIndex will let you decide how you find the index. The main difference between findIndex vs indexOf in JavaScript is that findIndex accepts a callback as an argument, and indexOf accepts a value as an argument. What is the difference between findIndex vs indexOf in JavaScript? Now, let’s get stuck in and see what the differences are between findIndex vs indexOf. In this post about findIndex vs indexOf in JavaScript we are going to look at the differences between the method and the method.īefore we get stuck into this article I have two posts, how to get the index of an item in an array in JavaScript, and how to get the index of an object in an array in JavaScript, that go into detail about how to use both of these methods and I would highly recommend having a read of them after this post. As you know there are two helpful methods for finding an index in a JavaScript array, but which one should you use?














Javascript array findindex