Lodash is one of the most popular utility-belt library. It can make you very productive and effective in writing Javascript programs.
Read Lodash's page on npm here. How many times was it downloaded just last week alone?
Let's create a data array withthe contents: 1,2,3,4,5. This array has 5 items.
To get the first item, we can use lodash's _.first.
return _.first(data)
The result is 1.
To get the first 3 elements, we can use lodash's _.take
return _.take(data, 3)
The result is 1,2,3.
Let's create a data array consisting of objects.
We can dump the content using the dump
filter.
[{"name":"John","age":45},{"name":"Mary","age":32},{"name":"Peter","age":54}]
To retrieve the name field from each object in this array, lodash's _.pluck is very handy.
return _.pluck(data, 'name')
The result is John,Mary,Peter.
We can even display the result nicely as a bullet list
Using _.find, we can look up an object by its field.
Let's try to find out how old Mary is.
return _.find(data, {name: 'Mary'})
Mary is 32 years-old.
Now it's your turn to take the following learning challenges.
The data is
[{"name":"John","age":45},{"name":"Mary","age":32},{"name":"Peter","age":54},{"name":"Jane","age":12}]
// replace this code with your solution that uses lodash
return _.pluck(data, 'age')
The names are 45,32,54,12
// replace this code with your solution that uses lodash
// hint: use _.pluck and _.min
var ages=_.pluck(data, 'age')
return _.min(ages)
The youngest age is 12.
// replace this code with your solution that uses lodash
var ages=_.pluck(data, 'age')
return _.max(ages)
The oldest age is 54.
// replace this code with your solution that uses lodash
// hint: use your previous solution with _.find
var ages=_.pluck(data, 'age')
var minAge=_.min(ages)
return _.find(data, {age: minAge})
The youngest person is Jane.