Syntax, Parameter and Return Value
Syntax:
_.map(collection, [iteratee=_.identity])
Parameters:
-
collection (Array|Object|string): The collection to iterate over.
- [iteratee=_.identity] (Function): The function invoked per iteration.
Return Value:
(Array) - Returns the new mapped array.
Examples
Mapping Array Elements:
JavaScript
var _ = require('lodash');
var numbers = [1, 2, 3];
var doubled = _.map(numbers, n => n * 2);
console.log(doubled);

You can also try this code with Online Javascript Compiler
Run Code
Output:
[2, 4, 6]
Demonstrates multiplying each number in an array.
Extracting Properties from Objects:
JavaScript
var users = [{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 40 }];
var ages = _.map(users, 'age');
console.log(ages);

You can also try this code with Online Javascript Compiler
Run Code
Output:
[36, 40]
Shows how to extract a specific property from each object in an array.
Mapping Over an Object:
JavaScript
var object = { 'a': 1, 'b': 2, 'c': 3 };
var valuesSquared = _.map(object, n => n * n);
console.log(valuesSquared);

You can also try this code with Online Javascript Compiler
Run Code
Output:
[1, 4, 9]
An example of applying a function to each value in an object.
Mapping Over a String:
JavaScript
var string = "hello";
var asciiValues = _.map(string, char => char.charCodeAt(0));
console.log(asciiValues);

You can also try this code with Online Javascript Compiler
Run Code
Output:
[104, 101, 108, 108, 111]
Demonstrates mapping each character in a string to its ASCII value.
Frequently Asked Questions
How does _.map() differ from native JavaScript Array.map()?
Lodash's _.map() works with a broader range of collections, including objects and strings, whereas the native Array.map() is limited to arrays.
Can _.map() modify the original collection?
No, _.map() returns a new array and does not modify the original collection, adhering to the principles of functional programming.
Is _.map() efficient for large datasets?
_.map() is generally efficient for large datasets, but performance depends on the complexity of the iteratee function and the size of the dataset.
Conclusion
Lodash's _.map() method is a versatile and essential tool for transforming collections in JavaScript. It offers a concise and readable way to apply a function to each element of a collection, producing a new array of transformed elements.
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.