JavaScript - Calculating the total of numbers within a row and down a column

Is there a way to calculate the sum of values in each row and column and create a new array (potentially one-dimensional) with the results?

New Array [
    [ 1, 1, 0, 1 ],
    [ 1, 1, 1, 1 ],
    [ 1, 1, 1, 1 ],
    [ 1, 1, 0, 1 ]
]

Answer №1

let result = [];  //a single-dimensional array to store the sums
let hArray = [
   [ 1, 1, 0, 1 ],
   [ 1, 1, 1, 1 ],
   [ 1, 1, 1, 1 ],
   [ 1, 1, 0, 1 ]
]; //sample array

let vArray = []; //Creating an array of arrays with the columns of hArr

for (let j=0; j<hArray[0].length; j++) {
  let temp = [];
  for (let i=0; i<hArray.length; i++) {
      temp.push(hArray[i][j]);
  }
  vArray.push(temp);
}

//calculate sum of elements in each line - Vertically and Horizontally
function calculateSumVH (hIndex, vIndex) {
  let total = 0;
  //add horizontal elements
  for(let i=0; i<hArray[hIndex].length; i++) {
    total += hArray[hIndex][i];
  }
  //add vertical elements
  for(let i=0; i<vArray[vIndex].length; i++) {
    total += vArray[vIndex][i];
  }
  return total;
}

// loop through the main array and get results
let sumResult = 0;
//sum of each row
for (let i=0; i<hArray.length; i++) {
   for (let j=0; j<hArray[i].length; j++) {
      sumResult = calculateSumVH(i,j);
      result.push(sumResult);
   }   
}

Please double-check now. The variable result contains the final output.

Based on my given array above, I expect a resulting array like 7, 7, 5, 7, 8, 8, 6, 8, 8, 8, 6, 8, 7, 7, 5, 7

The code currently does not include the element itself in the sum. To achieve the desired result as per your comment, kindly replace this line:

sumResult = calculateSumVH(i,j);

with

sumResult = calculateSumVH(i,j) - (2 * hArray[i][j]);

Thank you for your attention.

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

The validity of AngularJS form is constant and always returns true with formName.$valid

I am facing an issue with my Angular application form where even though the input fields are blank, formName.$valid is always true. Below is the HTML code for my form: <form name="contactForm" novalidate ng-submit="processForm(formData)" autocomplete=" ...

Ensure that an element exists in Selenium before proceeding with actions

Currently, I am undergoing testing with the Selenium web driver and one of the requirements is to wait for my object to be defined on the page. Important: There are no visible changes in the DOM to indicate when my object is ready, and it's not feasib ...

Utilizing Javascript / jQuery to eliminate specific CSS styles

I am facing an issue with the CSS code for a table positioned at the bottom of the screen. The current code includes a filter specifically for IE 8, but I need to make it compatible with IE 10 as well by removing the filter and adding a background color. ...

Transform the information sent from the server into a user-friendly interface using typescript on the frontend

Received data from the backend looks like this: id: number; user_id: number; car_brand: string; car_model: string; vin: string; equipment: string; reg_number: string; car_mileage: number; car_year: string; Meanwhile, the interface in the ...

Adding the AJAX response to the specified element's ID

I'm having trouble inserting radio buttons into a <div> on my page using an AJAX response. The code I have looks like this: // AJAX form for updating tests after category selection $('#categories').change(function(){ category_id ...

How should the array.sort(a, b) method be properly used after the recent updates in node.js version 11.0.0 and above?

After successfully running code and passing tests on node 10, we encountered issues when upgrading to node 11. The code, which maps over an array of objects and alters properties, now fails unit tests after the upgrade. The code should sort based on a stri ...

Morgan middleware in Express.js specifically targeting unsuccessful requests for logging purposes

Currently, I am facing an issue with my middleware setup in Express.js while using Morgan. The problem arises because Morgan is only logging requests that return error code 302 (redirected), which happens when my middleware encounters an error and redirect ...

What could be causing my Svelte store's subscribe() method to trigger despite no change in value?

One of the Svelte stores I am using is called activeAccountIndexStore: export const activeAccountIndexStore: Writable<number | "native" | null> = writable(null); Initially, the value of the store is null, but it gets set to either a spec ...

What is the reason for jQuery's ajax feature running scripts by itself?

Lately, I've observed an issue where jQuery functions seem to disappear if a jQuery ajax call is made immediately after injecting jQuery into an inner iframe. The functions like `.dialog()`, `.draggable()`, and other plugins stop working when the ajax ...

Unable to call trigger method in sub component within a slot due to issues with $refs functionality

I have customized a modal component with the following template: <template> <my-base-modal ref="BaseModal" :width="1000"> <template v-slot:header>Details</template> <template v-slot:body> <detail-card ref ...

Utilizing Dojo DGrid to customize the appearance of data within cells

I am facing an issue with my dgrid where I want to style cells by underlining the text when the checkboxes are selected for the row. My initial approach was to add a CSS class to the item once the checkbox is checked for the row. However, this method did ...

What could be the reason for the failure in my mocha/chai Error throwing test?

In my pursuit to test a simple javascript package, I encountered an issue. Despite wanting to verify if an Error is thrown during the test, it bizarrely gets marked as a failure when executed. Here's the snippet of code in question: var should = req ...

Slider Adjusts Properly on Chrome, but Not on Firefox

Visit this URL This link will take you to the QA version of a homepage I've been developing. While testing, I noticed that the slider on the page works perfectly in Chrome and IE, but has layout issues in Firefox where it gets cutoff and moved to th ...

Utilize Ajax to load an Ajax-driven page

Currently, I am in the process of developing a GreaseMonkey script for the ServiceNow CMS that includes jQuery/AJAX. The main purpose of this script is to retrieve the number of incidents using the filter option provided by ServiceNow for technicians throu ...

Ways to retrieve JSON string from responsetext in JavaScript

After spending the entire day on this, I still can't figure it out. I have AJAX that fetches a JSON string from a PHP script, but now I need to work with it in JavaScript. Here's what I've tried: var xmlhttp; xmlhttp=new XMLHttpRequest(); ...

What is the mechanism by which the useState hook in React determines the calling context?

After transitioning from using class components to functional components in React, I delved into the documentation with keen interest to understand how the useState hook functions. Upon consulting the FAQ page, it was explained that each component has an ...

In search of an easy method for retrieving corresponding segments of text from an array

Is there a simpler way to extract the digital part of strings from an array like array("HK00003.Day","HK00005.Day")? <?php $arr=array("HK00003.Day","HK00005.Day"); $result= array(); foreach ($arr as $item){ preg_match('/[0-9]+/',$item,$ma ...

Unlocking the value of the "input" field within an EventListener function in Angular directly from the DOM

In my "characters" module, there is a form with a text field and a button. When the button is clicked, it triggers a function but I am struggling to retrieve the current input text and pass it to the async function. HTML: https://i.sstatic.net/DMF8w.png ...

Struggling to retrieve multiple images from an array using axios

const Fs = require('fs') const Path = require('path') const Axios = require('axios') var dir = './tmp'; async function downloadImage () { if (!Fs.existsSync(dir)){ Fs.mkdirSync(dir); } var arr = ['http ...

Tips for showcasing a string value across various lines within a paragraph using the <br> tag for line breaks

I'm struggling to show a string in a paragraph that includes tags to create new lines. Unfortunately, all I see is the br tags instead of the desired line breaks. Here is my TypeScript method. viewEmailMessage(messageId: number): void { c ...