Lodash differenceBy Case-Insensitive String Comparison
This article explains how to configure the
_.differenceBy method in the Lodash JavaScript library to
compare strings without regard to their letter casing. By default,
Lodash uses strict equality, making operations case-sensitive. By
passing a custom iteratee function or Lodash's built-in string
transformers, you can normalize your data during comparison and retrieve
the accurate array difference.
The Solution: Using an Iteratee
The _.differenceBy method accepts an iteratee as its
final argument. This iteratee is invoked for each element in the input
arrays to generate the criterion by which differences are computed. To
make the comparison case-insensitive, pass a function that normalizes
the strings to lowercase.
The most concise approach is using Lodash's _.toLower
method directly as the iteratee:
const _ = require('lodash');
const array1 = ['Apple', 'BANANA', 'cherry'];
const array2 = ['apple', 'Cherry'];
const result = _.differenceBy(array1, array2, _.toLower);
console.log(result);
// Output: ['BANANA']Using Native JavaScript Methods
If you prefer standard JavaScript without referencing Lodash's
internal string methods, you can supply an arrow function using
String.prototype.toLowerCase():
const result = _.differenceBy(array1, array2, (item) =>
typeof item === 'string' ? item.toLowerCase() : item
);Checking the type ensures that non-string values will not throw a runtime error during the transformation step.
Case-Insensitive Comparison with Object Arrays
If your strings are nested within objects, supply a function that accesses the target property and converts it to lowercase:
const users1 = [{ name: 'Alice' }, { name: 'BOB' }];
const users2 = [{ name: 'alice' }];
const result = _.differenceBy(users1, users2, (user) => user.name.toLowerCase());
console.log(result);
// Output: [{ name: 'BOB' }]The resulting array maintains the original casing and structure of the elements from the first array while excluding matches based on the normalized values.