2

I want to chain Lodash Array methods interchangeably with ES6 Array methods without using _chain and in a Functional Programming style.

I want to do this:

import {flatMap} from 'lodash';

const result = my2DimensionalArray.flatmap().map(i => {
 return `${i}-blergh`;
});

I get this isn't really possible without extending native Array Protoytpe.

I'm currently working like this:

import _ from 'lodash';

_(my2DimensionalArray).flatMap().value().map(i => {
  return `${i}-blergh`;
});

Can I improve this somehow? How are other people doing the same thing?

2 Answers 2

3

Because _.flatMap() returns an array, you can use JS map with it like this:

const arr = [[1, 3, 5, 7], [9, 11, 13, 15]];

const result = _.flatMap(arr) // returns an array
  .map(i => `${i}-blergh`); // JS map

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

If you're using a lodash's chain, use lodash's _.map() by moving _.value() to the end of the chain:

const arr = [[1, 3, 5, 7], [9, 11, 13, 15]];

const result = _(arr) // start a chain
  .flatMap()
  .map(i => `${i}-blergh`) // lodash's map
  .value(); // end the chain

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

Note: The array methods - map, filter, reduce, reduceRight, forEach, every, and some are part of ES5, and not ES6.

Sign up to request clarification or add additional context in comments.

2 Comments

Wow, so simple. And if the Lodash method you choose to use appeared in the middle of the chain?
As long as you're returning an array, you can chain JS methods. Whenever you use lodash chain, you can chaing only lodash methods. So you can chain together many lodash methods, end the chain with a value to return an array, and continue to chain JS method. You did that with your 2nd example.
1

ECMAScript 2019 introduced flat (and also flatMap which requires a mapper callback) so such operations can now be done with native methods:

const arr = [[1, 3, 5, 7], [9, 11, 13, 15]];
const result = arr.flat().map(i => `${i}-blergh`);
console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.