liveBook · Manning

Arraysdiff

As explained in Build a Frontend Web Framework (From Scratch)

A book-specific JavaScript function that compares two arrays and identifies items removed from the old array and added to the new array without treating order as significant.

arraysDiff compares two JavaScript arrays as unordered collections. It reports items added to the new array and items removed from the old array, making it useful for patching virtual-node properties such as CSS classes. section 7.5 section 8.5

The function has two small responsibilities:

  • Filter newArray for values that oldArray does not include, producing added. section 7.5
  • Filter oldArray for values that newArray does not include, producing removed. section 7.5
  • Treat a changed item as removal of the old value plus addition of the new value. section 7.5

Class-array diff

For an old array containing A, B, and C and a new array containing A, D, and E, the result is added: D and E; removed: B and C. A is unchanged. The implementation uses newArray.filter with includes for additions and oldArray.filter with includes for removals. section 7.5

Listing 7.3 Finding the differences between two arrays (utils/arrays.js)
export function arraysDiff(oldArray, newArray) {
  return {
    added: newArray.filter(
      (newItem) => !oldArray.includes(newItem)      #1
    ),
    removed: oldArray.filter(
      (oldItem) => !newArray.includes(oldItem)       #2
    ),
  }
}

The complete utility listing shows the two filter-and-includes operations that implement the comparison. section 7.5

This simplified comparison does not report insertion or removal indexes. That is sufficient for adding and removing classList entries, but class order can affect which styles override others; preserving order requires a more robust approach. section 7.5

How Build a Frontend Web Framework (From Scratch) covers it

How deep it goes
Implements two filter-and-includes passes, but stops short of preserving item indexes or class order.
Examples
Uses old and new class arrays where A remains, B and C disappear, and D and E appear.
What it assumes
Assumes familiarity with JavaScript arrays, virtual nodes, CSS classes, and DOM patching.
What you can do after
Build it from scratch in JavaScript to report unordered array additions and removals for DOM updates.
How it connects
Connects virtual DOM, DOM patching, CSS classes, objectsDiff, and arraysDiffSequence.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build a Frontend Web Framework (From Scratch). The section links point to the parts of the book it draws on.