Array Find Methods in JavaScript

Level 4282 keystrokes

This uses find to get an element and findIndex to get its position.

JavaScript code

// Array of user objects
1const users = [
2 { id: 1, name: "Alice", active: true },
3 { id: 2, name: "Bob", active: false },
4 { id: 3, name: "Carol", active: true }
5];
6
// find() returns the first element that matches the condition
// Returns undefined if no match found
7const found = users.find(u => u.id === 2);
// found is { id: 2, name: "Bob", active: false }
8console.log(found.name);
9
// findIndex() returns the index of the first matching element
// Returns -1 if no match found
10const index = users.findIndex(u => u.name === "Carol");
// Carol is at index 2
11console.log(index);

Output

Bob
2
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.

  • =× 11
  • :× 9
  • ,× 8
  • "× 8
  • .× 7
  • ;× 5
  • (× 4
  • )× 4
  • {× 3
  • }× 3

More JavaScript examples at level 4

← JavaScript typing practice