liveBook · Manning

Linear search

As explained in Grokking Simplicity

A search algorithm that examines elements sequentially until a matching element is found or the collection is exhausted.

Linear search examines an array sequentially for an item. Extracting this loop into indexOfItem() makes the search reusable while keeping cart-specific knowledge in one lower-level function. section 8.7

Searching a shopping cart

indexOfItem(cart, name) returns the matching array index or null when no item matches. remove_item_by_name() can then delegate removal to that result, while isInCart() converts it into a boolean. section 8.7

function remove_item_by_name(cart, name) {
    var idx = indexOfItem(cart, name);
 
    if(idx !== null)
        return removeItems(cart, idx, 1);
    return cart;
}
 
function indexOfItem(cart, name) {
    for(var i = 0; i < cart.length; i++) {
      if(cart[i].name === name)
        return i; #1
    }
    return null;
}

Browse the extracted JavaScript implementation, including sequential comparison, index return, and the null result for an exhausted collection. section 8.7

How Grokking Simplicity covers it

How deep it goes
Works through extraction, return values, layer structure, and reuse, then defers a more general loop version.
Examples
Uses shopping-cart lookup, item removal, membership testing, and price updates as concrete search clients.
What it assumes
Assumes familiarity with arrays, for loops, object properties, and indexing while making their relationship explicit.
What you can do after
Apply it via a reusable indexOfItem() function that returns an index or null for cart-based operations.
How it connects
Connects linear search with arrays, data structures, abstraction, code reuse, and stratified design.

Also explained in

Compare how 5 books explain linear search →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Simplicity. The section links point to the parts of the book it draws on.