What is the process for finding the total of numerous arrays?

I need help solving an equation that involves adding numbers from a list of randomly generated arrays, following the indices.

Each array in the list consists of four fixed-length random numbers:

const list = [
  [2, 9, 1, 2],
  [2, 3, 9, 4],
  [4, 7, 8, 1]
]

My goal is to calculate the sum of each number at every index across all arrays. For example:

const list = [
  [2, 9, 1, 2],
  [2, 3, 9, 4],
  [4, 7, 8, 1]
]

// Expected Result: [8, 19, 18, 7];

Can you provide guidance on how to accomplish this task?

Answer №1

Using the `map()` method on the initial array, this code snippet showcases a unique approach by nesting it with the `reduce()` function to calculate the sum of each corresponding column.

const list = [
  [2, 9, 1, 2],
  [2, 3, 9, 4],
  [4, 7, 8, 1]
];

const sums = list[0].map((x, idx) => list.reduce((sum, curr) => sum + curr[idx], 0));

console.log(sums);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Answer №2

const list = [
  [2, 9, 1, 2],
  [2, 3, 9, 4],
  [4, 7, 8, 1],
];

const result = list.reduce((a, b) => a.map((c, i) => c + b[i]));

console.log(result);

Update: there was a request for an explanation.

To start off, the reduce function receives an array (of arrays) and aims to condense it into a single value (also an array). In order to achieve this, it executes the first arrow function twice. The initial call will have a as [2,9,1,2] and b as [2,3,9,4]. The first arrow function then operates on a and b, resulting in a map of a. Considering that a is an array, the output will be a new array where each element is summed with the corresponding element from array b. This outcome will be [4,12,10,6]. Subsequently, reduce proceeds to invoke the first arrow function again with the recent result of the map operation: [4,12,10,6] as a and the final array element from the input [4,7,8,1] as b. Similarly to before, this arrow function combines elements from both arrays, resulting in another array where each a element is added to its respective element in b. The subsequent map returns [8,19,18,7]. As all input elements have been utilized, reduce concludes by returning this final value (the array).

Answer №3

If you want to achieve the desired outcome, try using the following approach that involves utilizing two loops with forEach.

const blockList = [[2, 9, 1, 2], [2, 3, 9, 4], [4, 7, 8, 1]];
const result = [];

blockList.forEach((v, index) =>
  v.forEach((val, i) => {
    result[i] = result[i] ? result[i] : 0;
    result[i] += val;
  })
);

console.log(result);

Check out the code on CodePen - here

Answer №4

If you need to manipulate arrays in JavaScript, consider utilizing the reduce and forEach methods.

In this example, we create an array where specific elements are added to particular indexes, allowing us to extract values from the object efficiently.

const list = [[2, 9, 1, 2],[2, 3, 9, 4],[4, 7, 8, 1]]

let op = list.reduce((op,inp)=> {
    inp.forEach((e,i)=> op[i] = op[i] ? op[i]+e : e)
    return op
},[])

console.log(op)

Answer №5

To efficiently sum up the values from multiple arrays, you can utilize .reduce with a for...of loop to extract the index and value of each inner array by utilizing the entries method. Then, simply assign them based on their indexes to an accumulator Array and calculate their sum.

let totalSum = list.reduce((acc, arr) => {
 for(let [index, num] of arr.entries()) acc[index] = (acc[index] || 0) + num;
 return acc;
}, []);

const list = [
  [2, 9, 1, 2],
  [2, 3, 9, 4],
  [4, 7, 8, 1]
]

let totalSum = list.reduce((acc, arr) => {
 for(let [index, num] of arr.entries()) acc[index] = (acc[index] || 0) + num;
 return acc;
}, []);

console.log(totalSum);

Answer №6

Implement a solution using nested loops:

const blocklist = [[2,9,1,2], [2,3,9,4], [4,7,8,1]], calculatedBlocks = [];
for (let j = 0, sum = 0; j < blocklist[0].length; j++, sum = 0) {
  for (let i = 0; i < blocklist.length; i++) sum += blocklist[i][j];
  calculatedBlocks.push(sum);
}

console.log(calculatedBlocks);

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

Emphasize entries in an index that match the currently visible content as you scroll

I have a table of contents in my HTML page with the CSS attribute position: fixed;. I want to emphasize the current reading position by highlighting it (bold or italics) as I scroll down the page. | yada yada yada ... 1. Secti ...

Pointer and integer comparison results in a compiler error

I'm trying to validate user input to ensure it falls within the range of 1 to 20, but I encountered a compile error when attempting to compile my code: Error: ISO C++ forbids comparison between pointer and integer Below is the code snippet causing ...

What is the best way to choose a specific word in a single row from a column that contains an array?

I need to filter a column that stores arrays of strings based on a specific keyword. However, when I attempt to do this, I encounter the following error: function contains(character varying[], unknown) does not exist Below is the query I am using: SELECT ...

Exploring the differences between scoping with let and without any scoping in

Within my code, there is a forEach loop containing a nested for loop. It's interesting that, even though I have a statement word = foo outside of the for loop but still inside the forEach loop, I can actually log the value of word after the entire for ...

If I use jQuery's ajax method to send a CSV file to my Node.js + Express server, where would the file be stored on the server?

I need help with sending a CSV file from my client to my Node.js and Express server using jQuery's ajax POST method. Once the CSV file reaches the server, I am unsure of how to access it. My objective is to pass the CSV file into my route's middl ...

Angular's ng-repeat orderBy and groupBy features are not functioning correctly for sorting

Currently, I am utilizing Angular's ng-repeat along with groupBy and orderBy. My goal is to sort by SeatNo ascendingly as in 1, 2, 8, 12 but Angular seems to be giving me 1, 12, 2, 8 instead. Note: I am aware that SeatNo is a string and have attempte ...

Issues with properly closing connections in Node.js, Socket.IO, and MySQL result in unnecessary database overhead

I've been grappling with this challenge for the past few months, and still haven't been able to crack the code. It appears that there's a surge in connections to our database, presumably due to improper closure of connections leading to exte ...

How to exchange variables and trigger events between jQuery and C# using AJAX

Hey there! So I've got this jQuery snippet that's using jqvmaps to display a world map and interact with it: <script type="text/javascript" lang="js> $(document).ready(function(){ jQuery('#vmap').vectorMap( ...

Navigational mapping tool with interactive user interface

I'm currently utilizing geomap to visualize the location using the following code snippet: function OnLoad() { $.ajax({ type: "POST", **url: "CS.aspx/CreateWorldMap"**, data: '{}', ...

The issue with AngularJS array filtering remains unresolved

How can I get this filter to function properly? <div ng-repeat="rvs in reviews | filter:{ Name:'{{ r.Name }}' }"> {{ rvs.Name }} </div> 'r.Name' is retrieved from another array "r in restaurants" However, instead of usin ...

Determing the dimensions of the browser's scroll bar

I have come across a query regarding the calculation of browser scrollbar sizes. However, my focus is on understanding how the solution in the npm package called scrollbar-wdith actually works. Can someone provide an explanation for this? To give some con ...

Utilizing a Search feature with Express and Node within the MVC framework

On the customers page of my website, I have implemented a search bar that sends the admin's input as a GET request. The goal is to find all data in the MySQL database that includes the entered string within the fullname field. The website is built us ...

Enable users to provide ratings ranging from 0.5 up to 5

I recently created a rating component that allows users to rate on a scale from 0 to 4.5, with increments of 0.5, which is causing unexpected behavior. I actually want users to be able to rate from 0.5 to 5 instead. How can I achieve this adjustment? Below ...

Adding a new element to an array in Swift can be done by either

What is the best way to add data into the array var tempArray = [[],[],[]]? I attempted to add this data tempCart[0] = (uuid as? NSArray)! //string tempCart[1] = (fileName as? NSArray)! //string tempCart[2] = (imageData as? NSArray)! //NSData How ...

Having trouble with updating array elements in MongoDB using $inc?

Everything seems to be running smoothly when I manually set the value to 5 and update the third element in the array: BasicDBObject setDoc = new BasicDBObject(); setDoc.append("array.3.view_counter", 5); However, upon attempting to use $inc to dynamicall ...

Issue with Bootstrap side navbar not collapsing when clicked on a link

Currently, I'm working on creating a website for a friend. While I used to have some experience with coding in the past, it has been a while and I am a bit rusty. This time around, I decided to use bootstrap for the project. However, I'm struggli ...

Place the Div directly above a distinct Div

Hey there! I'm currently working on positioning one div on top of another div programmatically (using javascript or css). These divs are completely separate and have the following structure: <div class="bottom"> <img src="image"></i ...

Apologies, but there seems to be an issue as no default engine was specified and no extension was provided in

I recently embarked on backend web development and decided to practice with a project using Node.js and Express.js. Here is the code I have in my app.js file: const express = require("express") const bp = require("body-parser") const ap ...

Is it possible for Javascript to locate a concealed Field within ASP.NET?

Trying to save the disabled property value of a hidden field in order to track the disabled state of a button between postbacks, using the following JavaScript function TrackState(buttonID) { var trackingField = document.getElementById("_tracking" + b ...

Is there a way to remove unnecessary code from the end of a string using JavaScript?

Most of the users of my script are hosted on a server that inserts a text ad at the end of each page. Unfortunately, this code is appearing in my script's AJAX responses as well. The unwanted content is an HTML comment followed by a link to their sign ...