Sub topic 3
Finding by Condition: find, findIndex, findLast, some, and filter
This chapter assumes you know arrow functions and object property access, and that you have seen comparator functions in the sorting chapter.
Predicate Search
A predicate is a function that returns true or false for each element. indexOf and includes only match exact values. Predicate methods match any condition you can write as a predicate.
const orders = [
{ id: 1, status: 'paid', total: 40 },
{ id: 2, status: 'pending', total: 15 },
{ id: 3, status: 'paid', total: 90 }
];
console.log(orders.find(o => o.status === 'paid').id); // 1
console.log(orders.findLast(o => o.status === 'paid').id); // 3
console.log(orders.findIndex(o => o.total > 100)); // -1
console.log(orders.some(o => o.status === 'pending')); // true
console.log(orders.filter(o => o.total > 20).length); // 2| Method | Returns | Stops early? |
|---|---|---|
| `find` / `findLast` | First / last match, or `undefined` | Yes |
| `findIndex` / `findLastIndex` | Position, or `-1` | Yes |
| `some` / `every` | Boolean | Yes |
| `filter` | New array of all matches | No |
Binary Search on Sorted Arrays
Every method above is a linear scan, which takes O(n) time. When an array is sorted, binary search halves the range on each step and runs in O(log n) time.
function binarySearch(sorted, target, compare = (a, b) => a - b) {
let lo = 0;
let hi = sorted.length - 1;
while (lo <= hi) {
const mid = (lo + hi) >>> 1;
const c = compare(sorted[mid], target);
if (c === 0) return mid;
if (c < 0) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
const data = [2, 5, 8, 12, 23, 38];
console.log(binarySearch(data, 23)); // 4
console.log(binarySearch(data, 7)); // -1The precondition is that the array must be sorted with the same comparator you pass to the search. If the array is unsorted, or was sorted by a different rule, the search can return -1 for a value that is present.
Choosing a Search Strategy
If you check membership many times, build a Set once. Each lookup then takes O(1) time on average:
const allowed = ['admin', 'editor', 'viewer'];
const allowedSet = new Set(allowed);
console.log(allowed.includes('editor')); // true, O(n) per lookup
console.log(allowedSet.has('editor')); // true, average O(1) per lookupTo look up whole objects by a key, use a Map, for example new Map(orders.map(o => [o.id, o])).
Exercise
You need to know whether any order has a total above 50, and you do not need the order itself. Which method fits best, and why not filter?
Show answer
Use some(o => o.total > 50). It returns a boolean and stops at the first match. filter scans the whole array and builds a new array you would throw away.
Exercise
binarySearch([5, 2, 8], 2) returns -1. Why?
Show answer
The array is not sorted. At the first step, mid is index 1, which holds 2, so this call happens to return 1. The question's premise fails for this input, but in general an unsorted array breaks the precondition, and the search can skip the half that holds the target. Sort it first with the same comparator.