What is the best way to calculate the difference and total of all arrays within an array?

Within my array of arrays, I am trying to subtract all inner arrays a - b and then sum the results. For example: [[10,0],[3,5],[5,8]] would result in 10 - 0 = 10, 3 - 5 = -2, 5 - 8 = -3, giving a total of 10 + (-2) + (-3) = 5;

Here is my attempt:

 var el;
 return array.reduce((a, b) => a - b );

However, my result came out as NaN. Now I understand that trying to subtract an array from another array was not a good idea. I know how to achieve this using a 'for' loop or similar method, but my question is:

How can I accomplish this using reduce or other "modern" method?

Thank you for your help.

PS. Please excuse any errors in my English skills ;)

Answer №1

To implement the reduce() method, you can follow this example.

var elements = [[10,0],[3,5],[5,8]]
var total = elements.reduce((result, item) => result + (item[0] - item[1]), 0);
console.log(total)

Answer №2

This solution is extremely adaptable as it can handle nested arrays of any size without compromising the accuracy of the result.

const calculateSum = (arr) => arr.reduce((sum, subArr) => {
        sum += subArr.reduce((a, b) => a - b);
        return sum;
      }, 0);

let arrayOne = [ [10, 0], [3, 5], [5, 8] ],
    arrayTwo = [ [5, 4, 1], [3, 5, 5], [5, 8] ];
    
console.log(calculateSum(arrayOne));
console.log(calculateSum(arrayTwo));

Answer №3

Is this what you were looking for? You were getting close, but don't forget to set the initial value as 0 and deconstruct the inner arrays into variables a and b like shown below:

var matrix = [[10,0],[3,5],[5,8]];

var total = matrix.reduce((previous, [a, b]) => previous + (a - b), 0);

console.log(total);

Answer №4

let numbers = [[2,6],[8,3],[1,7]];
numbers.map(pair => pair[0] * pair[1]).reduce((x,y) => x + y)

Answer №5

To optimize the code, consider decreasing both the outer and inner arrays.

var array = [[8, 4], [5, 3], [7, 1]],
    result = array.reduce(function (r, a) {
        return r + a.reduce(function (x, y) {
            return x - y;
        })
    }, 0);

console.log(result);

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

Suggestions for changing sub-component data in Vue

I have a scenario where I am using a component with tabs inside. The Head component (parent) includes the following code: <v-btn @click="setSelectedTab('Set') "> ... <component :is="selectedTab"></component> ...

Getting a variable from outside of the observable in Angular - a step-by-step guide

I have an Observable containing an array that I need to extract so I can combine it with another array. this.builderService.getCommercialData() .subscribe( data=>{ this.commercialDetails = data; this.commercialDetailsArr ...

Storing the background color in a JavaScript variable

I've been experimenting with creating a fade in and out effect for a background image on a website. I've also been attempting to capture the background color of a div and store it in a variable. Here's what I have tried: elem = document.ge ...

Create a path on the Google Map that follows the designated route

I am looking for a solution similar to one found here: Sample However, I have been unable to find a suitable solution anywhere. The main issue is being able to follow the route in order to draw a line between two points. Can anyone provide guidance on ho ...

Issue with the successful execution of connection event handler in NodeJS and Socket.io?

When I look at my code in files named server.js and index.html, I notice that the io.on('connection') part is not executing the console.log method in its callback when I visit my server in the web browser. Take a look at the code snippets below ...

Any recommendations for updating input in a directive without relying on $broadcast?

I am currently facing an issue with my contact list on controller A. Whenever I select a contact, the contact's information gets broadcasted to controller B and also to the datepicker directive in controller B. Although this method works, I am wonderi ...

Can you provide guidance on achieving a gradient effect throughout the mesh, similar to the one shown in the example?

Check out my code snippet on JSFiddle: https://jsfiddle.net/gentleman_goat66/o5wn3bpf/215/ https://i.sstatic.net/r8Vxh.png I'm trying to achieve the appearance of the red/green box with the border style of the purple box. The purple box was created ...

How can data be transferred from child component inputs to a parent form in Angular's template-driven approach?

It seems like this should be a straightforward task, but I'm encountering conflicting instructions on how to achieve it. I have three child components, each with their own set of input controls that are supposed to feed into a parent component. Howeve ...

Retrieve the index of several callbacks created within a loop iteration

While working with an API function that requires a callback in a for loop, I encountered an issue where the callback needed to be index-specific. However, I couldn't alter the willCallBack function (as it's part of the API) and didn't want t ...

What is the process for removing an element from my Reducer Object?

I'm facing a challenge with my reducer object structure. Here's an example of what it looks like: clientData : { 1080 : [{ID : 1111,name : 'John'},{ID : 2222,name : 'Stan'},], 1090 : [{ID : 3333,name : 'Adam'},{ ...

When working with Angular 2 and Typescript, a common error message that may be encountered is "TypeError

Currently diving into Angular 2 and encountered a stumbling block while attempting to create a service. Despite my efforts in finding a solution, I seem to be missing something crucial. Error: A problem arises in angular2-polyfills.js:1243 with the error ...

A situation where the event onclick fails to occur within NextJS

index.js: function Home () { return <div> <html> <head> <title>Site</title> </head> <body> <div class= 'v5_3' onclick = "func_click()"></div> </b ...

Issues with syntax in AJAX programming can be a significant road

I have a function linked to an onclick button event. This function sends data via ajax to another php file. Everything was working smoothly until I tried to add an IF statement to the 'success' section, which would receive true or false from an e ...

An AngularJS directive designed to execute after a text input has been modified

I have integrated a bootstrap calendar datepicker that interacts with and updates an <input type="text"> field. As of now, when I use ng-change="myAngularExpression()", the function gets executed the moment the text box is selected. Is there a way t ...

What is preventing me from using memoization in the getServerSideProps of NextJS?

I'm currently using React along with NextJS to showcase a variety of products on a specific category page. While I am able to successfully fetch the products utilizing getServerSideProps, I am not fond of how it continuously requests the product cata ...

Unable to supersede CSS module styling using global or external stylesheets in React, Next.js, or React Native

I'm facing a challenge finding a solution to a basic issue. I have a component that is initially styled using a class from a *.module.css file. However, I want to replace this style with one from a global stylesheet or another stylesheet but I can&apo ...

What is the method to update an element when any of the items in an array is marked as "Confirmed"?

{submissions && submissions.files_set.map((el) => { if (el.confirmed_status === null) { return <DataToConfirm />; } else if (el.confirmed_status === "CONFIRMED") { return <DataSent />; } })} This ...

Utilizing Javascript to implement a tooltip feature for dynamically inserted text

I recently incorporated a brief jQuery tooltip plugin into my site. It consists of approximately ten lines of code and works smoothly, as demonstrated in this demo. However, I encountered an issue when attempting to add new text that should also trigger t ...

Obtain the chosen item from a Bootstrap4 dropdown menu by utilizing a button

I am struggling to get a button with dropdown working in Bootstrap4. Below is the HTML code: <div class="row" id="dropdown-box"> <div class="col-lg-6"> <div class="input-group"> <div class="input-group-btn" id="button-grou ...

Having trouble displaying an array in React.JS

I am facing issues with combining two arrays to add a label and its description without it getting all mixed up. The JSON data is imported into a database as "db" and everything appears jumbled together. [![I have attached an image to help explain my iss ...