Underscore.JS - indexBy method



Syntax

_.indexBy(list, iteratee, [context])

indexBy method gets the spilted lists grouped by index returned by the iteratee method provided.

Example

var _ = require('underscore');

var list = [{"title": "Learn Java", "Author": "Sam", "Cost": 100},
   {"title": "Learn Scala", "Author": "Joe", "Cost": 200},
   {"title": "Learn C", "Author": "Julie", "Cost": 300} ]

//Example 1. invoke indexBy method to get objects indexed by their cost
var result = _.indexBy(list, 'Cost');
console.log(result);

//Example 2. invoke indexBy method to get objects indexed by their author
result = _.indexBy(list, 'Author')
console.log(result)

Save the above program in tester.js. Run the following command to execute this program.

Command

\>node tester.js

Output

{
  '100': { title: 'Learn Java', Author: 'Sam', Cost: 100 },
  '200': { title: 'Learn Scala', Author: 'Joe', Cost: 200 },
  '300': { title: 'Learn C', Author: 'Julie', Cost: 300 }
}
{
  Sam: { title: 'Learn Java', Author: 'Sam', Cost: 100 },
  Joe: { title: 'Learn Scala', Author: 'Joe', Cost: 200 },
  Julie: { title: 'Learn C', Author: 'Julie', Cost: 300 }
}
underscorejs_processing_collection.htm
Advertisements