What is the best way to combine and calculate elements in an array that is nested within an array using a specific condition or rule?

I have a JavaScript array of arrays with different data types that looks like this:

let bigArray = [["A", "B", 221.67],["C", "B", 221.65],["B", "D", 183.33],["B", "A", 4900],["E", "B", 150],["A", "B", 150]] 
Now I need to add the third element (a number) if the first and second elements match with the next array's first and second elements, and also subtract the third elements if a reverse match is found.

The expected output will be:

let ans = [["B", "A", 4528.33],["C", "B", 221.65],["B", "D", 183.33],["E", "B", 150]]

The subarray ["B","A", 4528.33] is achieved by performing subtraction operation as 4900-221.67-150

In bigArray, there are arrays with repeated pairs of elements such as "A" and "B". For all matching subarrays, perform addition and for reverse matches, perform subtraction. Example: 4900-221.67-150

I have tried various methods but couldn't achieve the desired output consistently. Any assistance would be greatly appreciated. Thank you!

Answer №1

To maintain a standard key, grouping with sorted keys can be done to ensure the same order of part keys. Then, values can be added or subtracted accordingly.

If any value is negative, changing the keys and converting it into a positive value is necessary.

let data = [["A", "B", 221.67], ["C", "B", 221.65], ["B", "D", 183.33], ["B", "A", 4900], ["E", "B", 150], ["A", "B", 150]],
    result = Object.values(data.reduce((r, [a, b, v]) => {
        const key = [a, b].sort().join('|');
        if (r[key]) {
            r[key][2] += a === r[key][0] ? v : -v;
            if (r[key][2] < 0) r[key] = [r[key][1], r[key][0], -r[key][2]];
        } else {
            r[key] = [a, b, v];
        }
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Techniques for removing invalid characters from a JSON $http.get() request

While working with data from an external web-service, which I have no control over, I encountered a problem where names containing apostrophes were causing issues due to backslashes being added in the JSON response. JSLint.com confirms that the JSON struct ...

In order to delete a post within a Node.js application, you must double-click the delete button

Previously, a nodejs application was utilizing custom js confirms. I decided to replace those with confirms from Bootblox.js. When the delete post button is pressed, it prompts for confirmation, but does not remove the post immediately. It requires pressi ...

Ways to simultaneously apply fade in and fade out effects using CSS

body { background-image: url("background.jpg"); background-attachment: fixed; font-family: 'Roboto', sans-serif; color: #333333; } #container { height: 1000px; } /* HEADER WITH NAVIGATION BAR AND LOGIN OPTION */ #head { position: abso ...

what is the best way to display a chosen value in a dropdown menu using jQuery?

How can I display a value from a database in a select option? This code is written in PHP, JSON, AJAX, and JQUERY. $(document).on('click', '.edit_data', function () { var shop_id = $(this).attr("id"); $.ajax({ url: "&l ...

Unexpected behavior when using ng-if within ng-repeat

I am trying to use a repeater to display views in an accordion, with the requirement that the views be conditionally loaded. I attempted to add an ng-if condition to check if current == true on the repeater's elements, but it does not seem to work as ...

Unpack and retrieve multiple values

Currently diving into the world of JavaScript and exploring destructuring. My goal is to display the following in the console: "Name: Mike Smith, Father: Harry Smith" "Name: Tom Jones, Father: Richard Jones" Encountering an error ...

DayClick function in FullCalendar plugin is malfunctioning

I have been struggling to make the dayClick feature in the FullCalendar plugin function properly. Whenever I click on a day, nothing happens and I can't seem to figure out what mistake I am making. Even after clicking on a day, no alert message appear ...

Experiencing issues with recognizing HTML DOM functions during Jest testing

I encountered an issue that reads as follows: TypeError: document.querySelector is not a function This error occurred in the line below: selectElement = document.querySelector('#selectbox'); The purpose of this line is to retrieve the selec ...

Can you please explain the process of retrieving the value of an item from a drop-down menu using JavaScript?

I am currently developing a basic tax calculator that requires retrieving the value of an element from a drop-down menu (specifically, the chosen state) and then adding the income tax rate for that state to a variable for future calculations. Below is the ...

Creating user input fields with rich text formatting capabilities in Ruby on Rails

When dealing with rich text user input in Rails, what is considered the best approach? While Markdown seems promising, I am struggling to find a user-friendly editor for set up and unsure about how to properly sanitize the HTML. The sanitize helper still ...

Exploring the Process of Setting Up a Temporary Endpoint in Express

Currently, I am working with the node.js framework express and my goal is to establish a temporary endpoint. This can either be one that automatically deletes itself after being visited once, or one that I can manually remove later on. Any assistance wou ...

Challenges with 'this' reference in a requireif causing Vuelidate complications

     Need help with vuejs component using vuelidate and validations:     validations: {      invoice: {          dueDate: {              required,          },          tax: {              require ...

Unable to capture HTML form input in $_POST[]

I've encountered an unusual issue while transferring data from an email form (HTML5) to ajax/JSON and receiving false in order to prevent redirection to the php script after pressing the submit button. When I include commas between each data paramete ...

Combining Angular JS with JSP and Servelet

I have recently started learning Angular JS and I am attempting to combine it with JSP & Servlet. My goal is to create a simple code that retrieves data from an Action Class and displays it on the Index.jsp page. Below is my code: Index.jsp - <!DOCTYP ...

Exploring ways to utilize fetch results within a return statement in React

I have fetched data that is displayed as shown below. Now, I am trying to figure out how to render this fetch in the return statement within the results div. Does anyone have any ideas on how to achieve this? I attempted using a map function because I assu ...

Assigning and retrieving values from PHP arrays to access variable values

Forgive me for this introductory question. My issue is that I am trying to retrieve the value of the variable name within an array. For example: $fruits = array($apple, $mango, $banana); I then assign the same value to all elements in the array. for ($i ...

Struggling with an Ember project: dynamically populating a form field upon selection

Having never delved into the world of Ember and being relatively new to JavaScript, I've been attempting to transition my HTML and JS work into the Ember framework with the help of a friend. The initial goal of my project is to populate a text field w ...

Learning to extract URL parameters in ReactJS is a valuable skill

I am facing an issue with my React components - App and Contact. I need to display the ID on the contacts page that is passed through the route. However, when I use console.log(this.props) in the Contact component, it returns an empty object. import React ...

Maximizing the potential of NPM modules by harnessing the power of the package.json file

Currently, I am working on developing an NPM module for a command-line tool. Upon installation of the package, it is essential to access and read the user's package.json file. While I understand how to read the file syntactically, my main concern lies ...

Default value for nonexisting indices in a PHP array

One feature I really appreciate in Ruby is the Hash implementation where you can set a default value when initializing a Hash object. However, I am currently facing challenges trying to replicate this functionality in PHP. Below is my initial attempt which ...