book

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?

Examples

Array of numbers

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.

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?

// replace this code with your solution that uses lodash
return _.pluck(data, 'age')

The names are 45,32,54,12

Q. What is the youngest age?

// 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.

Q. What is the oldest age?

// replace this code with your solution that uses lodash
var ages=_.pluck(data, 'age')
return _.max(ages)

The oldest age is 54.

Q. Who is the youngest person?

// 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.