What is underscore.js?
Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects. - Excerpts from http://underscorejs.org/
Lets unleash power of underscore.js
  • You can download it from http://underscorejs.org/underscore.js

    OR
    1. npm install underscore
  • Use any editor to write HTML file, I prefer Sublime Text, but it's your choice
  • Case study: There are many restaurants in City with different cuisines, menu items etc. Let's find desired output from what we want:
    1. <!DOCTYPE html>
    2. <html ng-app>
    3. <head>
    4. <script type='text/javascript' src='angular.js'></script>
    5. <script type='text/javascript' src='controller.js'></script>
    6. </head>
    7. <body>
    8. <script type='text/javascript'>
    9. var restaurant = [{
    10. 'id': '0',
    11. 'restaurantName': 'Indian Delight',
    12. 'street': '123, Street1, 1st Avenue',
    13. 'menu': [{
    14. 'Roti': '5',
    15. 'Dal': '10',
    16. 'Veggies': '20'
    17. }]
    18. },
    19. {
    20. 'id': '1',
    21. 'restaurantName': 'Chinese Hut',
    22. 'street': '456, Street2, 2nd Avenue',
    23. 'menu': [{
    24. 'Dimsum': '10',
    25. 'Momos': '20',
    26. 'Soup': '15'
    27. }]
    28. },
    29. {
    30. 'id': '2',
    31. 'restaurantName': 'Italian Bistro',
    32. 'street': '789, 5th Block, 3rd Avenue',
    33. 'menu': [{
    34. 'Pasta': 15,
    35. 'Pizza': 20,
    36. 'Salad': 5
    37. }]
    38. }
    39. ]
    40. function GetAllRestaurant() {
    41. console.log(_.pluck(restaurant, 'restaurantName'));
    42. }
    43. function RestaurantTotalMenuItemPrice(id) {
    44. var RestaurantMenu = _.pluck(restaurant, 'menu')[id];
    45. //Find RestaurantMenu by passing id
    46. //output is object > [...]
    47. //sum prices of all items, therefore we'll get all values from Key Pair
    48. var prices = _.values(RestaurantMenu[0]);
    49. //now reduce values to sum
    50. var sum = _.reduce(prices, function(memo, num) { return memo + num; })
    51. console.log(sum);
    52. }
    53. function TotalRestaurant() {
    54. console.log(_.size(restaurant));
    55. }
    56. GetAllRestaurant(); //output : ["Indian Delight", "Chinese Hut", "Italian Bistro"]
    57. RestaurantTotalMenuItemPrice(2); //output : 40
    58. TotalRestaurant(); //output : 3
    59. </script>
    60. </div>
    61. </body>
    62. </html>