Lodash 101
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?
It was downloadeed 4,326,487 times.
Examples
Array of numbers
Let's create a data array with the 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.
Array of objects
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
- John
- Mary
- Peter
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.
Challenges
Now it's your turn to take the following learning challenges.
Data
The data is
[{"name":"John","age":45},{"name":"Mary","age":32},{"name":"Peter","age":54},{"name":"Jane","age":12}]
Q: What are the ages of these people?
ages = _.pluck(data, 'age')
return ages
The ages are 45,32,54,12
Q. What is the youngest age?
min_age = _.min(ages)
return min_age
The youngest age is 12.
Q. What is the oldest age?
return _.max(ages)
The oldest age is 54.
Q. Who is the youngest person?
return _.find(data, {age: min_age})
The youngest person is Jane.