Skip to main content

transform

_.transform(iteratee, accumulator, object) # Ⓢ [Ⓣ][1] Ⓝ

An alternative to _.reduce; this method transforms object to a new



accumulator object which is the result of running each of its own



enumerable string keyed properties thru iteratee, with each invocation



potentially mutating the accumulator object. If accumulator is not



provided, a new object with the same [[Prototype]] will be used. The



iteratee is invoked with four arguments: (accumulator, value, key, object).



Iteratee functions may exit iteration early by explicitly returning false.

Since​

1.3.0

Arguments​

  1. iteratee (Function): The function invoked per iteration.
  2. accumulator (*): The custom accumulator value.
  3. object (Object): The object to iterate over.

Returns​

(*): Returns the accumulated value.

Example​

_.transform(function(result, n) {
result.push(n *= n);
return n % 2 == 0;
}, [], [2, 3, 4]);
// => [4, 9]

_.transform(function(result, value, key) {
(result[value] || (result[value] = [])).push(key);
}, {}, { 'a': 1, 'b': 2, 'c': 1 });
// => { '1': ['a', 'c'], '2': ['b'] }