JavaScript: Implementing lodash/fp flow to retrieve a collection of objects

Currently, I am in the process of transitioning a series of functions from _.chain to _fp.flow. However, I am encountering some challenges when dealing with currying complex objects within the flow. My goal is to:

  1. Transform an array of objects using grouped functions like countBy or
    sumBy</code) into a dictionary format (e.g. <code>{ group1:10, group2:15... }
    )
  2. Convert this dictionary into an array of key/value pairs (e.g.
    [{column: 'group1', value: '10'}, ...]
    )
  3. Sort the data based on a certain variable in either ascending or descending order

However, despite my efforts, the output object ends up being flattened into a lengthy array. The code snippet below shows part of the problem. While the reducer function successfully groups the values as intended, it seems that the interaction between the each step and orderBy is somehow flattening the object (the desired object structure appears correct after the _.each console.log).

I have included a sample of the code in the linked 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);

On a side note, I utilize ES6 syntax and React in my main project, which may impact the approach I take towards solving this issue.

https://jsfiddle.net/moc0L5ac/

Answer №1

To improve the code, it is recommended to utilize the map function instead of each. Additionally, ensure that the order of [value, column] is corrected to [column, value].

const newData = _.flow(
  _.reduce(transformer, {}),
  _.toPairs,
  _.map(([column, value]) => {
      const outputObject = {
        value: value,
        column: column
      }
      return outputObject;
    }),
  _.orderBy(['value'], [sortingDirection])
)(inputData);

Answer №2

Based on my understanding, this is the solution you are aiming to achieve

const inputData =
  [ { target: 123, groupby: 'a' },
    { target: -123, groupby: 'b' },
    { target: 123, groupby: 'a' },
    { target: -123, groupby: 'b' } ]

const columnsData = _.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(columnsData(inputData));
// => [ { column: 'a', value: 246 },
//      { column: 'b', value: -246 } ]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Forecast the width of an element using JavaScript

Is there a way to display tab elements on a webpage without them automatically wrapping into a new row if there are too many? Instead, I would like an arrow icon to appear at the end of the tabs so users can cycle between tab groups. The challenge is that ...

Incorporate time zone awareness to JavaScript date objects

Whenever I create objects in my MongoDB using Mongoose, the dates are displayed in the format of, for example, 2016-10-10T15:35:52.764Z (alternatively, it could be yyyy-MM-ddTHH:mm:ssZ). When I utilize Date.now() in JavaScript, I am given a timestamp. Is ...

Using vuex to paginate through firestore data and seamlessly update the state with new information

After taking advice from Tony O'Hagan on Stack Overflow, I integrated the following code to exhibit a paginated query: bindUsers: firestoreAction(({ bindFirestoreRef }) => { return bindFirestoreRef('users', Firebase.firestore().c ...

Postponing the execution of a controller until all JSON files have been fully loaded

I am currently trying to grasp the concepts of AngularJS, so my question might not be perfect. Is it feasible to delay the execution of a controller until the json files are fully loaded in a separate function? Below is the controller code: app ...

Challenges with communication between Ajax and Axis2

I've been struggling to obtain results from this specific Ajax command, but unfortunately, I have not been successful. $.ajax({ type: "get", url: "http://[localhost]:80**/*****/getdata.jws", data: 'method=s**& ...

Modifying td background color according to values in a PHP array

Trying to update the background color of a td element with the code below. However, it seems that the code needs some adjustment as the color is not being applied. Any assistance or alternative solutions would be greatly appreciated. Snippet of PHP code: ...

Display information using an ASP.Net barcode scanner

Currently, I am developing a WCF service application that involves receiving characters from a barcode reader and displaying the data on the UI for the user. My issue arises when inputting data using the keyboard into a textbox; everything functions corr ...

Is there a way to invoke a function once grecaptcha.execute() has completed running, but in response to a particular event?

Presently, the JavaScript function grecaptcha.execute is triggered on page load, as shown in the first example below. This means that the reCAPTCHA challenge occurs as soon as the page loads. A more ideal scenario would be to trigger it when the form submi ...

Tips for generating an ecosystem.json file for a node.js express app with pm2 that launches with npm start command

I am looking to utilize pm2 for my node.js express app. Although I can successfully start the server using npm start, I want to set it up in the ecosystem.json file so that I can manage it with pm2 and run it in cluster mode. One thing to note is that I c ...

Develop an engaging billboard carousel using jQuery

After coming across a tutorial on tympanus, I decided to make some modifications to create a rotating billboard effect. However, something seems to be going wrong and it's driving me crazy trying to figure out the problem! $(function() { $('#ad_ ...

Toggle visibility of table row upon user click (HTML/JQuery)

Having an issue with showing or hiding table rows using jQuery. I would like it so that when a user clicks on a table row with id="jobtitle", the corresponding tr with class="texter" will either show up or hide if it is already displayed. This is my curre ...

When attempting to call a recursive method in Vue with a changing `this` object, an error is thrown: "RangeError: Maximum call stack size exceeded"

Update integrate codePen into the project. https://codepen.io/jiaxi0331/pen/xxVZBMz Description encountered an issue while trying to call the parent method recursively Code export default { methods: { dispatch(componentName, event, value) { ...

Step-by-step guide for activating a text box when a check box is marked

I'm looking to activate and deactivate two text boxes when a check box is selected. Currently, only one text box is enabled when the check box is checked. How can I modify my code to enable and disable two text boxes based on the check box status? Her ...

What is the method for breaking a statement within an if statement on Blogger when both the IF and ELSE conditions are met?

I'm making some adjustments to the labels on my blog to ensure that each post has at least two labels. The concept is that if a post has LABEL 1, it will load one script, otherwise it will load another. However, I've encountered a situation wher ...

Error encountered: The Jquery-ui functionality ceases to operate upon the completion of content

I'm utilizing the jQuery UI library to rearrange the items on my list. Initially, everything works smoothly without any issues. However, when I navigate to another page and then return to the page with my list, I encounter difficulties. It's wor ...

Substitute the comma with a space

Here is my input code snippet: (((text(text here))) AND (test3) Near (test4) NOT (test5) NOT (Test6)),((tttt,tttt)),((and,lol)),((hbhbhbhbhbh)) This is the output I get: (((text(text here))) AND (test3) Near (test4) NOT (test5) NOT (Test6) (tttt,tttt) (an ...

The basic jQuery script seems to be malfunctioning

I am trying to attach an on click event to an li element using jQuery. I have written a simple jQuery code within the document ready function, but for some reason it is not functioning as expected. I have checked in both Chrome and Firefox, and there are n ...

Issue with JQuery delay functionality not activating correctly upon clicking an <a> tag

When I click on an <a> tag, I want to display a div and wait for 10 seconds before redirecting. However, the div is currently being shown immediately without waiting. Here is the HTML code: <a class="clickHereToDisplay" href="http://www.google.c ...

Changing the 'badge' to 'panel' within the UI framework of 'ant design' has been set

Can the Badge be placed next to 'Info' in a Panel using ant design? https://i.sstatic.net/Lldc7.png View Code <div> <Collapse> <Panel header="Info" key="1"> <Badge count={4} style={{ b ...

Vue: Conditionally display a division depending on v-if, excluding cases where the div returns null

Within my HTML, I have implemented conditional rendering using v-if <div v-if="showdiv"> <p>Content 1 appears here</p> </div> <div v-if="!showdiv"> <p>Content 2 appears here</p> < ...