Tech
Forums
Jobs
Books
Events
Interviews
Live
More
Learn
Training
Career
Members
Videos
News
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Underscore.js Tutorial
WhatsApp
Guest User
4y
8.2
k
0
0
25
Blog
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
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:
<!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];
//Find RestaurantMenu by passing id
//output is object > [...]
//sum prices of all items, therefore we'll get all values from Key Pair
var
prices = _.values(RestaurantMenu[0]);
//now reduce values to sum
var
sum = _.reduce(prices,
function
(memo, num) {
return
memo + num; })
console.log(sum);
}
function
TotalRestaurant() {
console.log(_.size(restaurant));
}
GetAllRestaurant();
//output : ["Indian Delight", "Chinese Hut", "Italian Bistro"]
RestaurantTotalMenuItemPrice(2);
//output : 40
TotalRestaurant();
//output : 3
</script>
</div>
</body>
</html>
Underscore.js tutorial
Up Next
Using Datatable JS For Showing List/ Table Data With Action (Edit/ Delete) Buttons
Ebook Download
View all
Frontend Developer Interview Questions and Answers
Read by 940 people
Download Now!
Learn
View all
Membership not found