0

I'm looking for lodash function that able to transform/map/filter a single value with array of functions, for example:

given value to be: " a, b ,c"

and then call lodash with function like: _.transform(value, functionList)

which functionList is array of functions to split and trimEach.

expected result is ['a', 'b', 'c'].


UPDATE:

Thanks for @vlaz, _.flow() is that what I'm looking for.

The example I gave above is illustrated the purpose of function. I'm not looking for how to split and trim string (sorry, may be my english is not good enough).

To answer my own questions (and my example), the example code is:

function split(v) {
    return v.split(',')
}
function trimStrArray(v) {
    return _.map(v, _.trim)
}
var fn = _.flow([split, trimStrArray])

console.log(fn(" a, b ,c"))
<script src="https://cdn.jsdelivr.net/lodash/4.15.0/lodash.min.js"></script>

Thanks to everyone.

2
  • You can compose functions using _.flow, is that what you are looking for? Commented Sep 19, 2016 at 10:24
  • @vlaz that's it. Thanks Commented Sep 19, 2016 at 10:25

2 Answers 2

1

You can achieve it using Array.prototype.reduce() or _.reduce(). The reduce is invoked on the array of functions:

function transform(value, functionList) {
  return functionList.reduce(function(result, fn) {
    return fn(result);
  }, value);
}

var value = " a, b, c";

function split(value) {
  return value.split(',');
}

function trimEach(value) {
  return value.map(function(item) {
    return item.trim();
  });
}

var functionList = [split, trimEach];

var result = transform(value, functionList);

console.log(result);

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

Comments

0

You could use _.split, _.map and as callback _.trim;

var string = " a, b ,c",
    result = _.map(_.split(string, ','), _.trim);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

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.