Utilizing Lodash in TypeScript to merge various arrays into one cohesive array while executing computations on each individual element

I am working with a Record and attempting to perform calculations on these values.

Here is an example input:

   const input1 = {
      key1: [
        [2002, 10],
        [2003, 50],
      ],
    };
    const input2 = {
      key1: [
        [2002, 20],
        [2003, 70],
      ],
    };
    const input3 = {
      key1: [
        [2002, 5],
        [2003, 60],
      ],
    };

For each key, I want to calculate the following for each specific year:

year => input1 + input2 - input3
// output: 2002 => 25, 2003 => 60

To achieve this, I have been experimenting with lodash/fp.

map(a => a.map(nth(1)))(map('key1')([input1, input2]))
// [[10, 50], [20, 70], [5, 60]]

Is there a way to pass the inputs and iterate over them, then get a callback function to retrieve the values needed for the calculation?

I have tried using zip and zipWith, but have not made much progress. Any suggestions on what I can do in this scenario? Thank you for your assistance.

Answer №1

To achieve the desired result, you can first create an object using the _.fromPairs method and then utilize the _.mergeWith function to perform addition and subtraction operations.

const input1 = {
  key1: [
    [2002, 10],
    [2003, 50],
  ],
};
const input2 = {
  key1: [
    [2002, 20],
    [2003, 70],
  ],
};
const input3 = {
  key1: [
    [2002, 5],
    [2003, 60],
  ],
};


const [one, two, three] = _.map([input1, input2, input3], ({key1 }) => _.fromPairs(key1))
const add = _.mergeWith(one, two, (a, b) => a + b)
const sub = _.mergeWith(add, three, (a, b) => a - b)

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

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

value assigned to ng-model does not update beyond its scope

My issue involves binding an ng-model to an input field. Despite this, the value of the variable it is connected to does not update outside of the specific div where the directive is defined: <div input-field ng-if="startTypes.selected.value == &a ...

What if the v-on:click event is applied to the wrong element?

I'm attempting to manipulate the anchor tag with jQuery by changing its color when clicked, but I'm struggling to correctly target it. <a v-on:click="action($event)"> <span>entry 1</span> <span>entry 2</span> ...

Unlocking the potential of the Bootstrap search dropdown

Currently, I am utilizing the following code to create a searchable dropdown menu. I found helpful guidance in this forum post. I am seeking advice on how to retrieve the value of the selected option. For example, if 'China' is chosen, I would l ...

Is it possible to utilize Ajax submit requests within a (function($){...}(jQuery)); block?

As a PHP developer with some knowledge of JavaScript, I am currently using AJAX to send requests to the server. I recently came across the practice of enclosing all code within an anonymous JavaScript function like: (function($){ //code here }(jQuery)). Fo ...

Ensure the button remains in focus after clicking on the input field: Material-Ui

I'm currently working with a material-ui dialog and I've encountered an issue. When I click on the input field, the social button loses focus which is not what I want. Here's how it looks: https://i.sstatic.net/vNRrP.png Here's the de ...

Problem with sorting when using $in operator in MongoDB

I am looking to retrieve documents from a MongoDB collection where the IDs match those in an array: [ '5f80a44d0179262f7c2e6a42', '5f8c00762fae890e9c4d029c', '5f802cf8abac1116a46bf9d4' ] The problem arises when the docu ...

Exploring ways to retrieve a function-scoped variable from within an Angular subscribe function

Here's the scenario: I have a simple question regarding an Angular component. Inside this component, there is a function structured like this: somethingCollection: TypeSomething[] ... public deleteSomething(something: TypeSomething): void { // so ...

Is there a way to mimic this type of scrolling effect?

Upon visiting this website, it is evident that the entire interface has been constructed with React. The scrolling experience on this site is exceptionally smooth, although it may feel slightly more substantial than a typical scroll. After researching onli ...

Issue encountered when trying to retrieve a database variable from a mapReduce operation in MongoDB

Greetings! I am currently developing an application that utilizes a MongoDB database. Within this database, there exists a user collection where all user data is stored. The structure of a document in this collection is as follows: { "_id" : ObjectId( ...

Sending data from the server to the client in MVC using C#

I sent a token from a View to a function in my HomeController, and now I need to process the token and send back the information to the frontend. I assumed that the resultData returned by the ajax call would be the output of GetMyData, but it turns out it& ...

You can see the JavaScript code directly in the browser

I'm completely puzzled as to why this is happening. How strange that the JavaScript code is visible on the browser, almost appearing like regular text on the web page. This mysterious occurrence seems to be exclusive to Firefox. Despite scouring vario ...

Unraveling the Mystery of Passing Props in React.js

Currently taking an online course to learn React, I encountered a unique scenario where one property is attached to another property in this manner: this.props.property01(this.props.property02) The tutor briefly touched on this code line, leaving me quit ...

Tips for finding documents in MongoDB using query filters

My website features a table where users can enter a word in a search field, prompting mongodb to search for matching words in specific objects and only return those results. The search text is included in the request query. Although the following code han ...

What is the best way to receive a user's input date in Dynamics 365 using HTML/JavaScript?

My HTML webform is set up to capture user input like address, card number, city, and state in text format. However, within Microsoft Dynamics 365, I have a custom entity with fields for this information. When a user completes the webform and submits it, a ...

Immersive image display

Currently on my website, I have a table displaying 9 images with descriptions. I'm looking to enhance user experience by allowing them to click on an image and view it in a larger format like a gallery without disrupting the layout of the page. This ...

Searching within a container using jQuery's `find` method can sometimes cause jQuery to lose control

I am trying to extract information from an input field within a table in a specific row. Here is the code I am using: var myElements = $('#myTable tbody').find('tr'); console.log(myElements); This correctly displays the items in the ...

Separate an undetermined length numpy 2D array into a 3D array

I am working with a numpy array of dimensions (18, 10525). It consists of 18 columns and 10525 rows; however, the number of rows may vary, making it necessary to slice the array into groups or windows of 200 rows for AI processing. For instance, I intend ...

Value in Hook not updating after memoization of parent component

Let's consider this scenario: import * as React from "react"; const useMyHook = ({ element }: { element: HTMLElement | null }) => { React.useEffect(() => { if (element) { console.log("element in hook", element); ...

Is your ListView working perfectly with a custom ArrayAdapter, but starts causing issues when you try to adjust the number of items?

I have a personalized ArrayAdapter that I use to handle my ListView: public class FilesAdapter extends ArrayAdapter<PutioFileLayout> { Context context; int layoutResourceId; PutioFileLayout data[] = null; public FilesAdapter(Contex ...

Clearing the require cache in Node.js using TypeScript

I need to repeatedly require a module in TypeScript and Node for testing purposes. I came across an approach on this post which suggests the following code snippet: const config = require('./foo'); delete require.cache[require.resolve('./fo ...