0

I am converting a _.chain group of functions to use _fp.flow, but am having some difficulty dealing with the way flow curries complex objects. I am trying to

  1. Reduce an array of objects with some grouped function (e.g. countBy/sumBy) into a object/dictionary (e.g. { group1:10, group2:15... } )
  2. Map it into an array of key/value pairs (e.g. [{column: 'group1', value: '10'}, ...])
  3. Sort by some variable into asc/desc order

but right now the resulting object ends up being flattened into a long array. A sample of the code is below. The reducer function in the code below is working correctly and grouping the values as I intended, but then I think the currying between the each step and orderBy is flattening the object somehow (the desired object is formed correctly after _.each in the console.log.

I've put a sample of the code in the attached JSFiddle.

const inData = [{ target: 123, groupby: 'a' },... }]; const colData = _.flow( _.reduce(reducer, {}), _.toPairs, _.each(([value, column]) => { console.log(value); console.log(column); const outObj = { value: value, column: column } console.log(outObj) return (outObj); }), _.orderBy(['value'], [sortDir]), // Have tried result with or without fromPairs _.fromPairs )(inData); 

PS: I am using ES6 syntax and React in my main project, if that makes a difference.

https://jsfiddle.net/moc0L5ac/

1
  • You should include sample data and expected output Commented Mar 25, 2017 at 4:26

2 Answers 2

1

You need to use map instead of each and also fix the order of [value, column] to [column, value]

const colData = _.flow( _.reduce(reducer, {}), _.toPairs, _.map(([column, value]) => { const outObj = { value: value, column: column } return outObj; }), _.orderBy(['value'], [sortDir]) )(inData); 
Sign up to request clarification or add additional context in comments.

Comments

1

To the best my understanding, this is what you're looking to accomplish

const inData = [ { target: 123, groupby: 'a' }, { target: -123, groupby: 'b' }, { target: 123, groupby: 'a' }, { target: -123, groupby: 'b' } ] const colData = _.flow( _.reduce((map, {target:v, groupby:k}) => Object.assign(map, { [k]: map[k] === undefined ? v : map[k] + v }), {}), _.toPairs, _.map(([column, value]) => ({ column, value })) ) console.log(colData(inData)); // => [ { column: 'a', value: 246 }, // { column: 'b', value: -246 } ] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.