Calling chain will cause all future method calls to return wrapped objects. When you’ve finished the computation, call value to retrieve the final value. Here’s an example of chaining together a map/flatten/reduce, in order to get the word count of every word in a song.

  1. var lyrics = [
  2. {line: 1, words: "I'm a lumberjack and I'm okay"},
  3. {line: 2, words: "I sleep all night and I work all day"},
  4. {line: 3, words: "He's a lumberjack and he's okay"},
  5. {line: 4, words: "He sleeps all night and he works all day"}
  6. ];
  7. _.chain(lyrics)
  8. .map(function(line) { return line.words.split(' '); })
  9. .flatten()
  10. .reduce(function(counts, word) {
  11. counts[word] = (counts[word] || 0) + 1;
  12. return counts;
  13. }, {})
  14. .value();
  15. => {lumberjack: 2, all: 4, night: 2 ... }

In addition, the Array prototype’s methods are proxied through the chained Underscore object, so you can slip a reverse or a push into your chain, and continue to modify the array.

chain

_.chain(obj) source

Returns a wrapped object. Calling methods on this object will continue to return wrapped objects until value is called.

  1. var stooges = [{name: 'curly', age: 25}, {name: 'moe', age: 21}, {name: 'larry', age: 23}];
  2. var youngest = _.chain(stooges)
  3. .sortBy(function(stooge){ return stooge.age; })
  4. .map(function(stooge){ return stooge.name + ' is ' + stooge.age; })
  5. .first()
  6. .value();
  7. => "moe is 21"

value

_.chain(obj).value() source

Extracts the value of a wrapped object.

  1. _.chain([1, 2, 3]).reverse().value();
  2. => [3, 2, 1]