Array find and findIndex in JavaScript

Level 3156 keystrokes

find() returns the first matching element, findIndex() returns its index.

JavaScript code

// Create an array of user objects
1const users = [{ id: 1 }, { id: 2 }, { id: 3 }];
// find() returns the first element where callback returns true
// Returns { id: 2 } or undefined if not found
2const user = users.find(u => u.id === 2);
// Print the found user object
3console.log(user);
// findIndex() returns the index of the first match
// Returns 1 (second element) or -1 if not found
4console.log(users.findIndex(u => u.id === 2));

Output

{ id: 2 }
1
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • =× 10
  • .× 6
  • ;× 4
  • (× 4
  • )× 4
  • :× 3
  • {× 3
  • }× 3
  • ,× 2
  • >× 2

More JavaScript examples at level 3

← JavaScript typing practice