JavaScript - Add up and combine an unspecified number of arrays in one concise statement

Have you ever come across the answer to the question about the Javascript version of Python's zip function? It demonstrates a clever method for merging any number of arrays into a single array through a concise statement.

zip= rows=>rows[0].map((_,c)=>rows.map(row=>row[c]))

In another interesting discussion, this question focuses on summing two arrays in a single iteration using a similar concept to zipping.

If we were to combine these approaches and handle an unknown number of arrays like:

[
  [1,2,3],
  [1,2,3],
  [1,2,3]
]

The desired outcome should be [3, 6, 9], which represents the summed values of corresponding elements from all input arrays. Let's assume each array has equal lengths for simplicity.

Answer №1

Just like many other responses, the solution can actually be simplified:

nums = [[1,2,3],[1,2,3],[1,2,3]];

var finalResult = nums[0].map(function(_, index) { 
  return nums.reduce(function(previous, currentRow) {
    return currentRow[index] + previous;
  }, 0);
});

console.log(finalResult);

Answer №2

After some consideration, I believe I have found a solution. This resource provided me with the necessary insight - by enhancing the original zipping method in the following manner:

zip = rows => rows[0].map((_,c) => rows.map(row=>row[c]).reduce((a,b) => a+b,0))

Answer №3

Start by transposing the arrays, swapping columns for rows and vice versa. Then, all you need to do is utilize the reduce function.

The initial code snippet is written in TypeScript for conciseness, while the second version switches over to JavaScript.

Remember that ES5's map and reduce functions are compatible only with IE9 and above.

var numbers = [[1,2,3],[1,2,3],[1,2,3]]

// TypeScript

var colSums = numbers[0].map(function(col, i) { 
  return numbers.map((row) => row[i]).reduce((a,b) => a + b );
});

// JavaScript

/*var colSums = numbers[0].map(function(col, i) {
  return numbers.map(function(row) {
    return row[i];
  }).reduce(function(a,b) {
    return a + b;
  });
});*/
document.getElementById("col-sums").innerHTML = colSums;
<p id="col-sums"></p>

Answer №4

You don't need to use map twice, a combination of two maps will achieve the same result:

Check out this Quick Demo

var m = [
  [1,2,3],
  [1,2,3],
  [1,2,3]
];

var total = m.map(function(arr, i) {
  var count = 0;
  return arr.map(function(el, idx) {
    return count += m[idx][i];
  })
}).pop()

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

`Is it possible to remove an empty frame using javascript?`

I have this script that generates a "layer" resembling a frame and I need to remove it. Here is the code for creating the layer: function disableLayer() { var layer = document.getElementsByTagName('div')[0]; d = document.createElement(& ...

Divide and store parts in an array

Is there a method to split a string at a specific character and include that character in the resulting array? For instance, if we split the string "hello ??? world" at ???, the resulting array would be ["hello ", "???", "world"]. It's worth noting ...

Error message: Issue with TypeScript and cleave.js - 'rawValue' property is not found on type 'EventTarget & HTMLInputElement'

I am encountering an error with the onChange event while implementing cleave in typescript. TypeScript is throwing an error indicating that 'rawValue' is not present in event.target. Here is my code: import React, { useCallback, useState, useEff ...

Retrieve data from Firestore using React and log it outside of the asynchronous function

Seeking a way to retrieve data from userRef and use it to initiate another asynchronous call to another document (e.g. bikes) in order to display that bikes doc on the page Currently, the userDetailslog in the Home screen function prints {"_U": ...

Getting Permission in the latest Facebook JavaScript SDK: A Step-by-Step Guide

I've been working on transitioning to the new Facebook JavaScript SDK from the old JavaScript library (where I was using Connect) and unfortunately, I'm facing issues with getting the permission dialog to pop up. My goal is to display the permiss ...

What might be preventing me from establishing a connection between MongoDB and nodejs on my localhost?

I am completely new to MongoDB and nodejs. I set up a simple database and attempted to connect it to my nodejs application but encountered the following error: MongoServerSelectionError: connect ECONNREFUSED ::1:27017 at Timeout._onTimeout (C:\Use ...

Tips for adjusting the size of a drawing on an HTML 5 canvas within a personalized Polymer component

In my custom Polymer element, I am looking to dynamically resize an html5 canvas when the window resize event occurs. Despite trying to utilize the window.onresize event, I encountered difficulties with accessing canvas functions. One of the functionalit ...

Dynamic array of fixed-sized arrays

I'm looking to make a member of my class a vector containing std:array, with the size of the array determined by a variable provided by the user. I tried using an initializer list, but encountered this error message: csvParser.cpp:18:35: error: inval ...

Is the vertex count of a Geometry in Three.js increased when it is converted to a BufferGeometry?

Recently, I've been experimenting with the fromGeometry method to convert regular Geometry objects into BufferGeometry objects. To my surprise, I noticed that the number of vertices increases during this conversion process. For instance, consider the ...

Challenges with fetching data from APIs in NextJs

I am currently working on a basic NextJs TypeScript application with the app router. The following code is functioning correctly: export default async function Page() { const res = await fetch("https://api.github.com/repos/vercel/next.js"); ...

Utilize Nuxt.js context within a Vue plugin

I have a situation where I'm working with Nuxt.js and have two plugins set up. In order to gain access to the VueI18n instance from lang.js within validate.js, I am in need of some guidance. Is there anyone familiar with how this can be accomplished? ...

Is there a way to invoke a method from within another method in VueJS 2 using mutations?

Currently facing an issue. I'm unsure of how to invoke a method within a mutation method. I attempted using this.show(), but it did not yield results. Is there a similar approach like in vuex actions where one can call a method within an action using ...

JavaScript 3D Arrays

Is there a way to create a 3D array similar to runes['red'][0]['test']? If so, how can I accomplish this? var runes = {} runes['red'] = [ 'test': ['loh'] ] runes['blue'] = {} runes[&apo ...

To maintain the width values (maximum width) when using overflow:auto, do not make any adjustments. (CSS for scrollbars

My English isn't the best and I'm just starting out with CSS. The scroll bar is taking up space and I want to prevent that from happening. I have noticed that when the scroll bar appears, it causes the fixed navigation menu bar to shift and the ...

Vue project missing required NPM dependency

Everything was going smoothly with my Vue project. However, when I changed the file name of one component, I encountered an error. After fixing the code, I restarted the npm server by running npn run serve. That's when the following errors popped up: ...

React search filter feature with dropdown selection

After successfully implementing a search filter in my React app, I encountered an issue when trying to incorporate a select tag to change the search filter criteria. class BookList extends Component { state = { search: '', selectedValue: ' ...

Retrieve the element that was clicked by targeting its class name using JavaScript

Unfortunately, I couldn't create this example in JSFiddle as it's currently in read-only mode. My goal is to identify the specific element that was clicked based on a given class. var button = document.getElementsByClassName("mybutton"); button ...

extracting arrays from references in mongoose

My challenge is that when I attempt to find() and print my entries, the arrays do not display properly. This is causing an issue as I need to send this information to my API. Here is the result I am currently getting: { "_id": "576287e5a3536e67 ...

Cancel all asynchronous requests

On my webpage, I trigger 15 ajax requests and have a button to cancel all pending ajax requests. According to the documentation, the abort() function terminates the request if it has already been sent. However, even after clicking the cancel button, I sti ...

How can I access a variable from a global.asax ASP.NET file in an Angular TypeScript file?

Is there a way to retrieve a variable from the .NET global.asax file and pass it into an Angular app that is part of the same project with just .ts and .html files? ...