transform source npm

_.transform(object, [iteratee=_.identity], [accumulator])

An alternative to _.reduce; this method transforms object to a new accumulator object which is the result of running each of its own enumerable properties through iteratee, with each invocation potentially mutating the accumulator object. The iteratee is invoked with four arguments:
(accumulator, value, key, object). Iteratee functions may exit iteration early by explicitly returning false.

Arguments

  1. object (Array|Object)

    The object to iterate over.

  2. [iteratee=_.identity] (Function)

    The function invoked per iteration.

  3. [accumulator] (*)

    The custom accumulator value.

Returns (*)

Returns the accumulated value.

Example

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

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