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?
var result 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
var result=_.take(data, 3)
return result
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.
var result= _.pluck(data, 'name')
return result
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.
var result= _.find(data, {name: 'Mary'})
return result
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 result=_.pluck(data, 'age')
return result
var result=_.pluck(data, 'age')
var min_age=_.min(result)
return min_age
The youngest age is 12.
var result=_.pluck(data, 'age')
var max_age= _.max(result)
return max_age
The oldest age is 54.
// replace this code with your solution that uses lodash
// hint: use your previous solution with _.find
var result=_.pluck(data, 'age')
var min_age=_.min(result)
var y= _.find(data, {age: min_age})
return y
The youngest person is Jane.