[JavaScript] Find and findIndex Usage Guide

目次

Overview

When you need to extract specific data from an array, such as an employee with a particular ID or the first record that matches a criteria, the find method is ideal. If you require the location (position) of that data within the array, findIndex is the correct choice. This guide demonstrates how to use these two methods effectively through a directory search system scenario.

Specifications (Input/Output)

Comparing find and findIndex

Both methods stop searching and return a result as soon as the callback function returns true.

MethodPurposeReturn Value (Found)Return Value (Not Found)
findGet the actual dataValue of the elementundefined
findIndexGet the position (index)Index (Number)-1

Callback Function Arguments

The callback function follows the structure (element, index, array) => boolean. It takes the search criteria as input and outputs the matching element or its index.

Basic Usage

1. Get the Element (find)

This is commonly used to find an object with a specific property within an array of objects.

const members = ['Kobayashi', 'Nakabayashi', 'Obayashi'];

// Find a member whose name includes "Naka"
const target = members.find(name => name.includes('Naka'));

console.log(target); // "Nakabayashi"

2. Get the Index (findIndex)

Use this when you need to know the order or location of an element.

const staffIds = [101, 202, 303, 404];

// Find the first index where the ID is 300 or greater
const position = staffIds.findIndex(id => id >= 300);

console.log(position); // 2 (The position of 303)

Full Code (HTML / JAVASCRIPT)

This system searches for an employee in the directory by their ID and displays their details along with their registration order in the list.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Employee Search System</title>
    <style>
        .search-card {
            font-family: 'Segoe UI', sans-serif;
            max-width: 450px;
            padding: 25px;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            background-color: #ffffff;
            box-shadow: 0 4px 6px rgba(0,0,0,0.05);
        }
        .input-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #555;
        }
        input[type="number"] {
            width: 100%;
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 6px;
            font-size: 1rem;
            box-sizing: border-box;
            transition: border-color 0.3s;
        }
        input[type="number"]:focus {
            border-color: #4a90e2;
            outline: none;
        }
        .result-area {
            padding: 15px;
            background-color: #f8f9fa;
            border-radius: 6px;
            min-height: 80px;
        }
        .found-name {
            font-size: 1.4rem;
            color: #333;
            margin: 0 0 5px 0;
            border-bottom: 2px solid #4a90e2;
            display: inline-block;
        }
        .found-meta {
            color: #666;
            font-size: 0.9rem;
            margin: 5px 0 0 0;
        }
        .error { color: #d9534f; font-weight: bold; }
    </style>
</head>
<body>

<div class="search-card">
    <div class="input-group">
        <label for="staff-id">Staff ID Search (1001+)</label>
        <input type="number" id="staff-id" placeholder="Please enter ID">
    </div>

    <div id="search-output" class="result-area">
        <p>Search results will appear here</p>
    </div>
</div>

<script src="employee_search.js"></script>
</body>
</html>

JavaScript

/**
 * Employee Search Script
 * Identifying data using find and findIndex
 */

// 1. Employee Database (Array)
const staffDirectory = [
    { id: 1001, name: 'Mori', role: 'Manager' },
    { id: 1002, name: 'Kobayashi', role: 'Assistant Manager' },
    { id: 1003, name: 'Oki', role: 'Chief' },
    { id: 1004, name: 'Nakamori', role: 'Member' },
    { id: 1005, name: 'Kogi', role: 'Member' },
    { id: 1006, name: 'Obayashi', role: 'Newcomer' }
];

// Get DOM elements
const idInput = document.getElementById('staff-id');
const outputArea = document.getElementById('search-output');

/**
 * Function to execute search
 * @param {number} queryId 
 */
const findStaff = (queryId) => {
    // Clear if no ID is entered
    if (!queryId) {
        outputArea.innerHTML = '<p>Search results will appear here</p>';
        return;
    }

    // ★ find method: Retrieve the object itself
    const staff = staffDirectory.find((person) => person.id === queryId);

    if (staff) {
        // ★ findIndex method: Retrieve the position in the array (0-based)
        const index = staffDirectory.findIndex((person) => person.id === queryId);
        
        // Display results
        outputArea.innerHTML = `
            <h3 class="found-name">${staff.name} (${staff.role})</h3>
            <p class="found-meta">
                ID: ${staff.id}<br>
                List Position: #${index + 1}
            </p>
        `;
    } else {
        // Not found
        outputArea.innerHTML = '<p class="error">No employee data found for this ID.</p>';
    }
};

// Monitor input events
idInput.addEventListener('input', (e) => {
    const val = Number(e.target.value);
    findStaff(val);
});

Custom Points

You can make search conditions more flexible by changing person.id === queryId to person.name === 'string' for name-based searches. It is also possible to implement complex logic such as find(p => p.role === 'Manager' && p.id > 1000) to search using multiple combined conditions.

Important Notes

The find and findIndex methods do not work in Internet Explorer (IE). If you must support legacy browsers, you should implement a Polyfill or use the filter method as a substitute. Regarding performance, these methods check the array from the beginning, so searching for data located near the end of a very large array (thousands of items) can be slow. For frequent searches in large datasets, it is recommended to convert the array into an object or a Map using IDs as keys.

Advanced Usage

Data Deletion with findIndex

When deleting data by ID from an array of objects, the splice method requires an index as an argument.

const users = [
    { name: 'Nakabayashi' },
    { name: 'Omori' }
];

// Want to delete 'Omori'
const targetIndex = users.findIndex(u => u.name === 'Omori');

if (targetIndex !== -1) {
    users.splice(targetIndex, 1);
}

console.log(users); // [{ name: 'Nakabayashi' }]

Summary

When working with specific data in an array, it is essential to choose the method that fits your goal. Use find when you want to display or access the detailed properties of an element. Choose findIndex when you need the index for updating or deleting an item. Because the return values differ significantly between an object (or undefined) and a number (or -1), you must ensure your conditional logic handles these results correctly. Mastering these tools is key to efficient array manipulation in JAVASCRIPT.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次