Friday, January 16, 2026
HomeLanguagesJavascriptLodash _.transform() Method

Lodash _.transform() Method

Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, lang, function, objects, numbers etc. 
The _.transform() method is an alternative to _.reduce() method transforms object to a new accumulator object which is the result of running each of its own enumerable string keyed properties through iteratee with each invocation potentially mutating the accumulator object. A new object with the same prototype will be used if an accumulator is not provided. 
Syntax: 
 

_.transform(object, iteratee, accumulator)

Parameters: This method accepts three parameters as mentioned above and described below:
 

  • object: It holds the object to iterate over.
  • iteratee: It is the function that the method invoked per iteration for every element.
  • accumulator: It holds the custom accumulator value.

Return Value: This method returns the accumulated value.
Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file.
 

javascript




// Requiring the lodash library
const _ = require("lodash");
 
// Original array
var object = [12, 13, 14];    
 
// Using the _.transform() method
let st_elem = _.transform(object,
            function(result, n) {
  result.push(n *= n);
  return n % 2 == 0;
}, []);
 
 
// Printing the output
console.log(st_elem);


Output:  

144, 169

Example 2:

javascript




// Requiring the lodash library
const _ = require("lodash");
 
// Original array
var object = { 'p': 3, 'q': 6, 'r': 3 };    
 
// Using the _.transform() method
let st_elem = _.transform(object,
    function(result, value, key) {
  (result[value] || (result[value] = [])).push(key);
}, {});
 
 
// Printing the output
console.log(st_elem);


Output: 

{ '3': ['p', 'r'], '6': ['q'] }

Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.

RELATED ARTICLES

Most Popular

Dominic
32474 POSTS0 COMMENTS
Milvus
117 POSTS0 COMMENTS
Nango Kala
6846 POSTS0 COMMENTS
Nicole Veronica
11977 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12062 POSTS0 COMMENTS
Shaida Kate Naidoo
6985 POSTS0 COMMENTS
Ted Musemwa
7219 POSTS0 COMMENTS
Thapelo Manthata
6933 POSTS0 COMMENTS
Umr Jansen
6911 POSTS0 COMMENTS