Syntax, Parameter and Return Value
Syntax:
_.invokeMap(collection, path, [args])
Parameters:
-
collection (Array|Object): The collection to iterate over.
-
path (Array|string): The path of the method to invoke or the function to invoke.
- [args] (...*): The arguments to invoke the method with.
Return Value:
(Array) - Returns the result of invoking the method on each element.
Examples
Invoking a Method on Array Elements:
JavaScript
var _ = require('lodash');
var strings = ['123', '456', '789'];
var parsedIntegers = _.invokeMap(strings, parseInt);
console.log(parsedIntegers);
You can also try this code with Online Javascript Compiler
Run Code
Output:
[123, 456, 789]
Demonstrates invoking parseInt on each string in the array.
Applying a Method to Objects in an Array:
JavaScript
var objects = [{ 'value': '10' }, { 'value': '20' }, { 'value': '30' }];
var values = _.invokeMap(objects, 'value.toString');
console.log(values);
You can also try this code with Online Javascript Compiler
Run Code
Output:
['10', '20', '30']
Shows invoking the toString method on a property of each object.
Using a Custom Function:
JavaScript
var numbers = [1, 2, 3];
var doubled = _.invokeMap(numbers, num => num * 2);
console.log(doubled);
You can also try this code with Online Javascript Compiler
Run Code
Output:
[2, 4, 6]
An example of invoking a custom function to double each number.
Invoking with Additional Arguments:
JavaScript
var collections = [['a', 'b'], ['c', 'd']];
var joinedStrings = _.invokeMap(collections, 'join', '-');
console.log(joinedStrings);
You can also try this code with Online Javascript Compiler
Run Code
Output:
['a-b', 'c-d']
Demonstrates invoking the join method with an additional argument.
Frequently Asked Questions
How does _.invokeMap() handle elements that don't have the specified method?
If an element doesn’t have the specified method, _.invokeMap() will return undefined for that element.
Can _.invokeMap() be used with a method that modifies the original elements?
Yes, if the invoked method modifies the elements, those changes will reflect in the original collection.
Is _.invokeMap() efficient for large collections?
_.invokeMap() is generally efficient, but its performance depends on the complexity of the method being invoked and the size of the collection.
Conclusion
Lodash's _.invokeMap() method is a powerful and flexible tool for uniformly applying a method or function to each element in a collection. It simplifies complex data transformations and method invocations, making code more concise and readable.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.