JavaScript's sequential addition of nested arrays

Having trouble adding together 4 nested arrays in JavaScript. The arrays are structured like this: x = [[Array1(9)], [Array2(9)], [Array3(9)], [Array4(9)]]

I am looking to "zip" them together and add the values. For example, I want to add Array1[0] with corresponding elements of Array2-4[0], and do this for all nine values in each array.

The arrays look like this:

[1, 2, 4, 3.6, 1.05, 4.65, 1.95, 0.5, 2.5]

[0.432, 0.602, 1.29, 1.146, 0.558, 1.43, 0.686, 0.178, 1.024]

The result would be something like:

[1.432, 2.602, etc...]

I've been struggling with using x.map() to accomplish this. Any assistance would be greatly appreciated.

Thank you,

Answer №1

If you want to iterate through the outer array, you can use Array.prototype.reduce() and then loop through each nested array using Array.prototype.forEach() to sum up the values of each nested array item with their corresponding items in the resulting array:

const src = [[1, 2, 4, 3.6, 1.05, 4.65, 1.95, 0.5, 2.5], [0.432, 0.602, 1.29, 1.146, 0.558, 1.43, 0.686, 0.178, 1.024]]

result = src.reduce((r,a) => (a.forEach((n,j) => r[j] = (r[j]||0)+n), r),[])

console.log(result)
.as-console-wrapper{min-height:100%;}

Answer №2

Utilizing for each loop for both outer and inner arrays

let arrayOne = [ [1, 2, 4, 3.6, 1.05, 4.65, 1.95, 0.5, 2.5],[0.432, 0.602, 1.29, 1.146, 0.558, 1.43, 0.686, 0.178, 1.024]]
let arrayTwo = [];
arrayOne.forEach((arr) => arr.forEach((innerArr, index) => {
if (!arrayTwo[index]) arrayTwo[index] = 0; 
arrayTwo[index] = arrayTwo[index] + innerArr;
}));
console.log(arrayTwo);

Answer №3

Utilize the initial array as a map and add corresponding values from the other three arrays to each value. You can create a custom function, such as sumArrays, to handle arrays of any length.

const arrays = getData();
let sums = arrays[0].map((v, i) => v + arrays[1][i] + arrays[2][i] + arrays[3][i]);
let sums2 = sumArrays(arrays);

console.log(sums);
console.log(sums2);

function sumArrays(arrays) {
 const checkLengthEquality = () => {
  let lengths = arrays.map(v => v.length);
  return Math.max(...lengths) === Math.min(...lengths);
 };

 if (!checkLengthEquality()) {
  throw Error("Arrays are not of equal length");
 }
 
 const sum = (v, i) => {
  let len = arrays.length;
  while(len-- > 1) {
    v += arrays[len][i];
  }
  return v;
 };
 
 return arrays[0].map((v, i) => sum(v, i));
}

function getData() {
  return [
    [1, 2, 4, 3.6, 1.05, 4.65, 1.95, 0.5, 2.5], 
    [0.432, 0.602, 1.29, 1.146, 0.558, 1.43, 0.686, 0.178, 1.024],
    [3.1, 2, 4.3, 3.8, 1.5, 6.5, 95, 1.5, 2.5],
    [12, 1, 1.3, 8, 5.3, 6.2, 5, 1, 2.3]
  ];
}
.as-console-wrapper { top: 0; max-height: 100% !important; }

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

Explore RxJs DistinctUntilChanged for Deep Object Comparison

I have a scenario where I need to avoid redundant computations if the subscription emits the same object. this.stateObject$ .pipe(distinctUntilChanged((obj1, obj2) => JSON.stringify({ obj: obj1 }) === JSON.stringify({ obj: obj2 }))) .subscribe(obj =& ...

Error in setting cookies using Javascript document.cookie on iOS with cordova-plugin-ionic-webview

Backend-sent cookies are successfully stored, but the app itself cannot set cookies. When running the code snippet below: document.cookie = "notified=1; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT"; console.log(document.cookie); An empty strin ...

What criteria should I consider when selecting a make for the createTheme components?

After reviewing the documentation for the createTheme component, I noticed examples with MuiButtonBase, MuiButton, and MuiSlider. However, when it comes to adding a button, it's simply called Button, not MuiButton. So, does this mean I just need to p ...

Siblings are equipped with the advanced selector feature to

I'm struggling to understand this setup I have: <div class="container"> for n = 0 to ... <a href="some url">Link n</a> endfor for each link in ".container" <div class="poptip"></div> ...

The GraphQL Resolver function that returns an object

When querying with GraphQL, I receive results in the following format: { "data": { "events": [ { "_id": "65f0653eb454c315ad62b416", "name": "Event name", " ...

Creating a basic bar graph using d3.js with an array of input data

In my dataset, I have an array of form data that includes items like 'Male', 'Female', 'Prefer Not To Say'. I want to create a simple bar chart generator using D3.js that can display the percentages or counts of each item in t ...

Error: Functionality cannot be achieved

Looking for assistance in resolving this issue. Currently, I am attempting to register a new user and need to verify if the username already exists or not. Below is the factory code used for this purpose: .factory('accountService', function($res ...

Animate images using mouse vertical movement

Creating websites is just a hobby for me, not something professional. Recently, I came across a beautifully designed website that had some unique features I hadn't seen before, like placing three images in one div (which I researched and learned how t ...

Triggering an automatic pop-up window using JavaScript based on a PHP condition

I have developed a hidden pop-up box that becomes visible when targeted, with its opacity increasing to one. I am aiming for the pop-up to appear if the user is identified as a "firstTimeUser," a status saved in a PHP $_SESSION variable. However, I am stru ...

Unsubscribe from the Event Listener in Node.js

In light of this inquiry (linked here), can the Listener be eliminated from within the callback function? To illustrate: let callback = function(stream) { if(condition) performAction(); else server.removeListener('connection', cal ...

Implementation of internationalization into a JSON-formatted data file

I recently integrated i18n into my application and I'm facing a challenge with implementing the useTranslation(); function in my navbar data file. This file serves as the database for the page titles and tabs, and I'm unsure about how to proceed. ...

The dropdown menu is not appearing in the correct position when clicked

https://i.stack.imgur.com/fMyZQ.jpg Hello there, this link appears normal before clicking on it. But once clicked, it moves to the top of the page like so: https://i.stack.imgur.com/yZ0R0.jpg You can clearly see the difference. I have also provided the c ...

React-Native has reached the maximum update depth, please check the new state

When I try to add and change the number (setNum(number+1)), I encounter an error message stating: Maximum update depth exceeded. This issue may arise when a component repetitively calls setState inside componentWillUpdate or componentDidUpdate. React enfor ...

Filling in a text field with the text content (rather than the value) from a dropdown menu

Presently, I have the select box with the id "title" populating a text field with the id "costcenter". The current code works perfectly fine when using the VALUE of the select box to trigger the population of the cost center field. However, my requirement ...

Two select boxes trigger multiple sorting operations

Struggling to implement 2 different sorting operations on two separate columns in a datagrid, using 2 different select boxes has proven to be challenging. I attempted the code below, but as a beginner, I was unable to solve it... In HTML: <select ng ...

Error message in Ionic 2: "Property is not found on type"

Currently, I am working on a project in Ionic 2 and have encountered a stumbling block with a seemingly simple task. My issue lies with a Textbox where I aim to input text that will then be displayed. I found some code on a website (http://www.tizag.com/j ...

Attempting to modify information in vue.js

I have been facing an issue with overriding data in the App.vue component. It seems that every time I try to update the data in my main.js file, the component still takes the default data. I am working with webpack as well. App.vue <template> & ...

The Lua UI text contains numerous strings, each with the presence of the word "or"

As a newcomer to Lua, I could really use some assistance with this script. It involves checking text on the player UI and works fine when it equals a specific value like game:GetService("Players").LocalPlayer.PlayerGui.Main.Border.ClassLabel.Te ...

Refresh my website's specific table automatically whenever the database is updated. Alternatively, reload the table every 2 seconds to ensure the latest values from the database are displayed

How can I update table values in real-time when the database in phpMyAdmin is updated? I have implemented some code that successfully updates the data on my webpage, but the issue is that the entire page reloads every 2 seconds. Is there a way to only ...

Generating a collection of arrays

I am unsure if this is the correct approach, but I aim to retrieve an array of arrays for later use in calling elements within another function. static Values RetrieveXML(string XMLFile) { using var reader = XmlReader.Create(XMLFile); r ...