Understanding Lodash invokeMap for Collections

The _.invokeMap method in the Lodash JavaScript library is designed to invoke a specific method on each element within a collection, returning an array containing the results of each operation. This article explains the primary purpose of _.invokeMap, how it operates on arrays and objects, the advantages it provides over standard JavaScript iteration methods, and practical examples demonstrating its implementation.

The Core Purpose of _.invokeMap

In modern JavaScript, developers frequently need to call a method on every item within a list—such as formatting strings, manipulating arrays, or executing an instance method on a series of objects. While native JavaScript allows this via Array.prototype.map(), it often requires verbose arrow functions or manual context binding.

The primary purpose of _.invokeMap is to streamline this pattern into a single, declarative function call. It iterates over a collection (either an array or an object), calls a specified method for each element, passes any provided arguments to that method, and compiles the returned values into a new array.

Syntax and Parameters

The basic syntax for _.invokeMap is:

_.invokeMap(collection, path, [args])

Practical Applications

1. Invoking Built-in Prototype Methods

_.invokeMap allows you to apply built-in prototype methods directly to items in a collection without defining inline callback functions.

const words = ['frontend', 'backend', 'fullstack'];

// Invoking String.prototype.toUpperCase
const uppercased = _.invokeMap(words, 'toUpperCase');
// Result: ['FRONTEND', 'BACKEND', 'FULLSTACK']

2. Passing Arguments to Methods

If the target method requires parameters, they can be supplied as subsequent arguments to _.invokeMap.

const numbers = [
  [3, 1, 2],
  [9, 7, 8],
  [5, 4, 6]
];

// Sorts each subarray in place and returns them
const sorted = _.invokeMap(numbers, 'sort');
// Result: [[1, 2, 3], [7, 8, 9], [4, 5, 6]]

const textSnippets = ['JavaScript', 'TypeScript', 'ECMAScript'];

// Slicing substrings by passing start and end indices
const sliced = _.invokeMap(textSnippets, 'slice', 0, 4);
// Result: ['Java', 'Type', 'ECMA']

3. Invoking Custom Object Methods

When working with class instances or plain objects that expose their own member functions, _.invokeMap cleanly triggers those methods across the entire dataset.

const users = [
  { name: 'Alice', getGreeting() { return `Hello, ${this.name}!`; } },
  { name: 'Bob', getGreeting() { return `Hello, ${this.name}!`; } }
];

const greetings = _.invokeMap(users, 'getGreeting');
// Result: ['Hello, Alice!', 'Hello, Bob!']

Advantages Over Native Methods