How to get index in a sorted array based on iterator function in JavaScript?

When working with sorted arrays in JavaScript, you often need to find the correct insertion position for a new element to maintain the sorted order. This article explores different methods to achieve this using iterator functions.

Using Binary Search for Insertion Index

The most efficient approach is to implement a binary search algorithm that finds the insertion point without modifying the original array.

function findInsertionIndex(arr, value, compareFunction) {
    let left = 0;
    let right = arr.length;
    
    while (left < right) {
        let mid = Math.floor((left + right) / 2);
        if (compareFunction(arr[mid], value) < 0) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }
    return left;
}

Example

<!DOCTYPE html>
<html>
<head>
    <title>Binary Search Insertion Index</title>
</head>
<body>
    <h3>Finding Insertion Index with Binary Search</h3>
    <p>Original array: [1, 3, 5, 7, 9]</p>
    <p>Value to insert: 6</p>
    <div id="result1"></div>
    
    <script>
        function findInsertionIndex(arr, value, compareFunction) {
            let left = 0;
            let right = arr.length;
            
            while (left < right) {
                let mid = Math.floor((left + right) / 2);
                if (compareFunction(arr[mid], value) < 0) {
                    left = mid + 1;
                } else {
                    right = mid;
                }
            }
            return left;
        }
        
        function compare(a, b) {
            return a - b;
        }
        
        var arr = [1, 3, 5, 7, 9];
        var valueToInsert = 6;
        var index = findInsertionIndex(arr, valueToInsert, compare);
        
        document.getElementById("result1").innerHTML = 
            "Insertion index: " + index + " (insert 6 at position " + index + ")";
    </script>
</body>
</html>

Using findIndex() for Custom Conditions

The findIndex() method can find the first position where a condition is met, useful for finding where a value should be inserted.

<!DOCTYPE html>
<html>
<head>
    <title>FindIndex Method</title>
</head>
<body>
    <h3>Using findIndex() Method</h3>
    <p>Finding insertion point for value 4 in [1, 2, 5, 7, 8]</p>
    <div id="result2"></div>
    
    <script>
        var arr = [1, 2, 5, 7, 8];
        var valueToInsert = 4;
        
        var index = arr.findIndex(element => element > valueToInsert);
        
        // If no element is greater, insert at the end
        if (index === -1) {
            index = arr.length;
        }
        
        document.getElementById("result2").innerHTML = 
            "Insert " + valueToInsert + " at index: " + index;
    </script>
</body>
</html>

Using sort() and indexOf() (Less Efficient)

This method works only if the value already exists in the array, as it finds the existing position rather than the insertion point.

<!DOCTYPE html>
<html>
<head>
    <title>Sort and IndexOf Method</title>
</head>
<body>
    <h3>Using sort() and indexOf() Methods</h3>
    <p>Finding existing value 3 in array</p>
    <div id="result3"></div>
    
    <script>
        function compare(a, b) {
            return a - b;
        }
        
        var arr = [5, 1, 3, 2, 4];
        var num = 3;
        
        arr.sort(compare);
        var index = arr.indexOf(num);
        
        document.getElementById("result3").innerHTML = 
            "Sorted array: [" + arr.join(", ") + "]<br>" +
            "Index of " + num + ": " + index;
    </script>
</body>
</html>

Comparison of Methods

Method Time Complexity Modifies Array? Works for New Values?
Binary Search O(log n) No Yes
findIndex() O(n) No Yes
sort() + indexOf() O(n log n) Yes No

Conclusion

Binary search provides the most efficient solution for finding insertion indices in sorted arrays. Use findIndex() for simpler cases, and avoid sort() + indexOf() for insertion purposes as it only works with existing values.

Updated on: 2026-03-15T23:19:00+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements