Ben
Ben

Reputation: 31

Using lodash to filter an object property

I'm trying to use the _.filter property to filter an array. I'd like to use the matchesProperty shorthand, but don't want to do a straight comparison.

eg. This works: .each(.filter(this.across, ['len', 3]), dostuff);

but if I want to filter values less than 9, I need to use a function: .each(.filter(this.across, function (o) {return o.len<9}), dostuff);

Is there a neater way to do this?

Upvotes: 1

Views: 744

Answers (1)

Damon
Damon

Reputation: 4336

I don't know what dostuff and this.across are, but let's assume you have an array of objects with property len and you want to filter values less than 9.

You can do this in a point free functional style, with just lodash, but it's going to look more convoluted than if you just use an arrow function. The matchesProperty shorthand only works for equality comparison, so can't be used in this case.

See both options below:

const arr = [
  { len: 2 }, // keep
  { len: 5 }, // keep
  { len: 9 },
  { len: 22 },
  { len: 8 } // keep
]

// point free functional style
const filtered = _.filter(arr, _.flow(_.property('len'), _.partial(_.gt, 9)))


// with arrow function
const filtered2 = _.filter(arr, o => o.len < 9)

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

Upvotes: 1

Related Questions