jgravois
jgravois

Reputation: 2579

loDash -- Is there a way to simplify for readability

I have the logic worked out but wanted to find a more readable (and maintainable) way to write this:

let labels = _.map(_.keys( _.groupBy(sd, 'month')), (i) => {
      return months[i].abr;
    });

Codepen

Upvotes: 1

Views: 116

Answers (2)

Robby Cornelissen
Robby Cornelissen

Reputation: 97341

Use method chaining:

const labels = _(sd).groupBy('month').keys().map(i => months[i].abr);

The following might semantically even better express your intention:

const labels = _(sd).map('month').uniq().map(i => months[i].abr);

const months = [
    {},
    {
      abr: 'Jan',
      full: 'January'
    },
    {
      abr: 'Feb',
      full: 'February'
    },
    {
      abr: 'Mar',
      full: 'March'
    },
    {
      abr: 'Apr',
      full: 'April'
    },
    {
      abr: 'May',
      full: 'May'
    },
    {
      abr: 'Jun',
      full: 'June'
    },
    {
      abr: 'Jul',
      full: 'July'
    },
    {
      abr: 'Aug',
      full: 'August'
    },
    {
      abr: 'Sep',
      full: 'Septmeber'
    },
    {
      abr: 'Oct',
      full: 'October'
    },
    {
      abr: 'Nov',
      full: 'November'
    },
    {
      abr: 'Dec',
      full: 'December'
    }
  ];

const sd = [
    { id: 1, year: 2017, month: 10, service: 3, val: 20 },
    { id: 2, year: 2017, month: 10, service: 1, val: 50 },
    { id: 3, year: 2017, month: 10, service: 2, val: 25 },
    { id: 4, year: 2017, month: 11, service: 3, val: 40 },
    { id: 5, year: 2017, month: 11, service: 1, val: 30 },
    { id: 6, year: 2017, month: 11, service: 2, val: 35 },
    { id: 7, year: 2017, month: 12, service: 3, val: 30 },
    { id: 8, year: 2017, month: 12, service: 1, val: 20 },
    { id: 9, year: 2017, month: 12, service: 2, val: 50 }
  ];

const labels1 = _(sd).groupBy('month').keys().map(i => months[i].abr);

console.log(labels1);

const labels2 = _(sd).map('month').uniq().map(i => months[i].abr);

console.log(labels2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Upvotes: 1

Gruff Bunny
Gruff Bunny

Reputation: 27986

It could be simplified for readability using chaining:

let labels = _(sd)
    .groupBy('month')
    .keys()
    .map(key => months[key])
    .value();

Upvotes: 0

Related Questions