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
- 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:
- There are lot of functions which you can use, I'm posting few examples for your reference:
- <!DOCTYPE html>
- <html ng-app>
- <head>
- <script type='text/javascript' src='angular.js'></script>
- <script type='text/javascript' src='controller.js'></script>
- </head>
- <body>
- <script type='text/javascript'>
- var restaurant=[
- {
- 'id': '0',
- 'restaurantName': 'Indian Delight',
- 'street': '123, Street1, 1st Avenue',
- 'menu': [
- {
- 'Roti': '5',
- 'Dal': '10',
- 'Veggies': '20'
- }
- ]
- },
- {
- 'id': '1',
- 'restaurantName': 'Chinese Hut',
- 'street': '456, Street2, 2nd Avenue',
- 'menu': [
- {
- 'Dimsum': '10',
- 'Momos': '20',
- 'Soup': '15'
- }
- ]
- },
- {
- 'id': '2',
- 'restaurantName': 'Italian Bistro',
- 'street': '789, 5th Block, 3rd Avenue',
- 'menu': [
- {
- 'Pasta': 15,
- 'Pizza': 20,
- 'Salad': 5
- }
- ]
- }
- ]
- function GetAllRestaurant () {
- console.log(_.pluck(restaurant,'restaurantName'));
- }
- function RestaurantTotalMenuItemPrice (id) {
- var RestaurantMenu=_.pluck(restaurant,'menu')[id];
-
-
-
- var prices=_.values(RestaurantMenu[0]);
-
- var sum= _.reduce(prices,function(memo, num){ return memo + num; })
- console.log(sum);
- }
- function TotalRestaurant () {
- console.log(_.size(restaurant));
- }
- GetAllRestaurant();
- RestaurantTotalMenuItemPrice(2);
- TotalRestaurant();
- </script>
- </div>
- </body>
- </html>