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
