Explain Codes LogoExplain Codes Logo

Get the index of the object inside an array, matching a condition

javascript
performance
optimization
best-practices
Alex KataevbyAlex Kataev·Oct 19, 2024
TLDR

To quickly get the index of the first object that meets a specified condition in an array, use findIndex():

const index = [{ a: 1 }, { a: 2 }].findIndex(obj => obj.a === 2); // psst... apparently, index prefers the number after 1, so it's 1.

This is a fast and efficient method for smaller arrays.

Performance optimization for larger arrays

However, if you are dealing with Goliath-sized arrays (read: very large arrays), the old-fashioned for loop can sometimes outperform findIndex(). This is because function calls can be costly in terms of performance in such scenarios:

let index = -1; for (let i = 0; i < largeArray.length; i++) { if (largeArray[i].a === 2) { index = i; break; // "Excuse me, I found what I was looking for. No need to carry on with the party!" } }

Harnessing the power of anonymous functions

It's not every day one can be anonymous and powerful. In JavaScript, anonymous functions give you that privilege. You can define dynamic conditions for your findIndex() function:

const isSeniorDev = person => person.title === 'Senior Developer'; // applying for promotion? const index = employees.findIndex(isSeniorDev);

This way, it's easier to define and reuse the condition outside the findIndex(), making your code cleaner and more readable.

Optimizing only when necessary. Yes, really.

MEMO: Optimization is not always a good thing! It can introduce unnecessary complexity. It's like bringing a bazooka to a knife fight. A bit of overkill, isn't it? Stick to findIndex() for smaller arrays and only bring out the big guns when you're dealing with large arrays.

Using some() when you want a bit more

Array#some can be useful when you need to find the index and perform some other calculations or side effects:

let index = -1; const exists = array.some((value, idx) => { if (value === "🏰") { index = idx; return true; // "Aha, I've seen this Castle in a Disney movie!" } return false; });

The some() functions stops the iteration once it matches the first true condition.

Using map to minimize full array iteration

Memo for efficiency seekers: Using map() can help reduce runtime when working with large arrays:

const map = new Map(array.map((val, index) => [val.id, index])); const index = map.get(someId); // "Good day, sir. I heard you were looking for an Id?"

Use lodash _.findIndex() for more complex find operations

lodash's _.findIndex() is like James Bond. It stylishly tackles complex conditions or nested properties:

const index = _.findIndex(array, {'user.details.age': 30}); // "Care for a martini, age thirty?"

Catering to the needs of Internet Explorer users

For folks who are still loyally using Internet Explorer, make sure to add a polyfill for Array.findIndex().

if (!Array.prototype.findIndex) { // code providing findIndex() functionality here }

Mixing indexOf() and map() for efficiency

Sometimes, a tag team of indexOf() and map() can efficiently help find the index based on property value:

const values = array.map(obj => obj.a); const index = values.indexOf(2);

Truncating indexes with bitwise operators like a boss

For those who like to show off, you can truncate decimal indexes with bitwise operators like ~~:

const index = ~~array.findIndex(value => value === "🏰"); // "I don't need no stinkin' decimal!"

Including edge cases in your search saga

Life is full of surprises. In JavaScript, finding an index can result in a 0, which, surprising as it might be, is falsy in JavaScript. So handle with care.

if (index !== -1) { /* it's a valid index, even if 0, it's not an insult */ }

Cross-indexing for improved lookups

When working with multiple arrays, you can cross-reference them to speed up your lookups:

const array1 = [{ id: 1, name: 'Apple' }, { id: 2, name: 'Banana' }]; const array2 = [1, 2, 1]; const array1IndexLookup = new Map(array1.map((value, index) => [value.id, index])); array2.forEach(value => { console.log(array1[array1IndexLookup.get(value)].name); // just printing some fruits. });

Be trendy, use ES2015/ES6 standards

After all, why wouldn't anyone want to be trendy? Array.findIndex() is a standard feature in ES2015/ES6 and modernizes your codebase:

// In the world of ES6 ME (More Efficient) const index = array.findIndex(ele => ele === "Feature");