For my use case, I needed to search through an array of objects and compare two (similar but not matching) objects:
As you can see one object has an approximate_size key/value, while the other does not. Now imagine trying to match these two using one line of code… I’ll spare you a headache, it’s hard to do. What saved my ass in this particular case was using findIndex().
What led me to the findIndex() method was trying (and ultimately failing) to use it’s younger brother: indexOf().
indexOf() can give you the index of an object in an array, but the objects need to have the EXACT same key/values. If a particular key/value exists in one, but not the other, it won’t work. Which makes sense, seeing as they techincally do not match.
What I was looking for was a way to match the values of the objects that I KNEW existed in both… This line of code will search our custom audience array and match against the ID, a value that we KNOW exists. The benefit here is that we can use findIndex to match similar objects rather than exact.
So there ya go… I learn quite a bit by messing around with side projects and using the latest technology.
Oh… “but why?”, you ask. So we can filter arrays of course! Oh and also for my react App. I’m building a Market research tool that allows users to create and save Facebook Audience Targeting Ad Settings. I used the findIndex method to dynamically filter an array of custom audiences, find a match and “check” a checkbox. See a screen shot below!
Originally published at www.alexdaro.com on August 20, 2018.
Create your free account to unlock your custom reading experience.