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}]
var x = _.pluck(data, 'age')
return x
The ages are 45,32,54,12
result = _.min(_.pluck(data, 'age'));
return result
The youngest age is 12.
var x = _.pluck(data, 'age');
result = _.max(x);
return result
The oldest age is 54.
// can I write the solution in one line?
return _.find(data, { 'age': _.min(_.pluck(data, 'age'))}, 'name');
The youngest person is Jane.