Adding up nested arrays based on their respective indices

If I have two nested arrays within a corresponding array like this:

const nums = [
    [4, 23, 20, 23, 6, 8, 4, 0],      // Each array consists of 8 items
    [7, 5, 2, 2, 0, 0, 0, 0] 
];

How can I add the values based on their indexes?

Expected Result:

// For example: 11 is from 4 (array1 - index1) + 7 (array2 - index1)
// and so forth.
[11, 28, 22, 25, 6, 8, 4, 0]

This is what I tried:

// While this solution works for two arrays,
// it wouldn't be dynamic enough to handle more than two arrays

const total = Array.from({ length: 8 }, (_, i) => nums[0][i] + nums[1][i]);

Answer №1

This code snippet demonstrates the ability to handle nested arrays.

const arr = [
  [4, 23, 20, 23, 6, 8, 4, 0],
  [7, 5, 2, 2, 0, 0, 0, 0],
  [2, 1, 2, 5, 7, 8, 9, 4]
];


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

console.log(sum);

Answer №2

Using the Array.map() method, we can transform each element of the first inner array into the sum of elements in the same column. To calculate the sum of elements in the same column, we employ the Array.reduce() function within the map():

const nums = [
  [4, 23, 20, 23, 6, 8, 4, 0],
  [7, 5, 2, 2, 0, 0, 0, 0],
  [1, 3, 4, 7, 1, 1, 1, 1],
];

let [first, ...rest] = nums;
let res = first.map((e, i) => rest.reduce((sum, x) => sum + x[i], e));

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

Answer №3

You can implement a solution utilizing a nested forEach() loop

const values = [
    [4, 23, 20, 23, 6, 8, 4, 0],
    [7, 5, 2, 2, 0, 0, 0, 0] 
];

function calculateSum(array){
  let max = Math.max(...array.map(x => x.length));
  let result = Array(max).fill(0);
  result.forEach((x,i) => {
    values.forEach(subArray => {
      result[i] = result[i] + (subArray[i] || 0)
    })
  });
  return result;
}

console.log(calculateSum(values));

Answer №4

To efficiently sum arrays by index, you can utilize the reduce method along with an inner loop in JavaScript. It's important to handle scenarios such as varying array lengths and non-numeric values.

const nums = [
    [4, 23, 20, 23, 6, 8, 4, 0],      // Each array consists of 8 items
    [7, 5, 2, 2, 0, 0, 0, 0] 
];
const otherNums = [
    [4, 23, 20, 23, 6, 8, 4, 0, 9, 55],      // Each array consists of 8 items
    [7, 5, 2, 2, 0, 0, 0, 0, "cat", null, 78],
    [7, 5, 2, 2, 0, 0, 0, 0, "dog", null, 78],
    [7, 5, 2, 2, 0, 0, 0, 0, "elephant", null, 78] 
];

const sumArraysByIndex = nums => nums.reduce((sums, array) => {
  for (const index in array) {
    if (sums[index] === undefined) sums[index] = 0
    if (isNaN(array[index])) return sums
    sums[index] += array[index]
  }
  return sums
}, [])

console.log(sumArraysByIndex(nums))
console.log(sumArraysByIndex(otherNums))

Answer №5

Find the shortest length of a subarray and then generate an array of that size, adding up the values using their indexes.

const nums = [
    [4, 23, 20, 23, 6, 8, 4, 0],
    [7, 5, 2, 2, 0, 0, 0, 0]
];

const [arr1, arr2] = nums;
const min = Math.min(nums[0].length, nums[1].length);

const output = Array.from({length: min}, (_, i) => arr1[i] + arr2[i]);

console.log(output);

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

experiencing an excessive amount of re-renders after transferring data to a distinct component

At the moment, I have implemented this logic to display data based on the results of a graphql query, and it is working well: const contacts = () => { const { loading, error, data } = useUsersQuery({ variables: { where: { id: 1 }, ...

Encountering an issue with displaying Firestore timestamps while utilizing onSnapshot() in React Native results in an error

Currently, I'm in the process of developing a chat application using Firestore. The approach involves utilizing Flatlist and querying with onSnapshot() to provide real-time updates for both sender and receiver. Here's an example of my query: con ...

Updating an item in the redux state is triggering a never-ending loop, leading to a browser

EXPECTED OUTCOME: My goal is to modify a value in my redux state ISSUE: I am encountering an issue where there is an infinite loop or the browser gets locked down. Despite consulting this Stack Overflow post and the official documentation, I am struggling ...

What causes queryAsync() to generate additional metadata?

Following the instructions provided in a response to a question, I utilized queryAsync() and it is functional. However, it is appending excessive meta data to my query result, which was initially a simple query. This is the code snippet I am using to exec ...

`Problem encountered when trying to present JSON content in an Android Gridview`

Encountering difficulties while attempting to showcase JSON data in a Gridview within an Android application using the Volley library through a URL. The error message received is: com.android.volley.NoConnectionError:java.io.IOException The JSON data i ...

Creating a Type in Typescript that Inherits Keys from Another Type

Imagine you're faced with this scenario involving a Typescript class: class Person { name: string; age: number; } If you were to create an object type with the same properties, using the any type, but with all properties being optional - how wou ...

Mongoose: when the item exists, increase the count; otherwise, add it to the array

Hey there, I've got a model setup like this: articles: [ { _id: { type: ObjectId, ref: "Article" }, amount: { type: Number } } ] The goal is to check if an article already exists in the array ...

Is it possible to generate a triangular attachment below a div element?

My designer sent me a unique design and I'm wondering if it's possible to replicate using HTML, CSS, or JavaScript? https://i.stack.imgur.com/spB71.png I believe it can be done with CSS by creating a separate div positioned absolutely under the ...

Troubleshooting the Width Problem in Bootstrap 5 Dropdowns

I am currently working on a new project and encountering an issue with the width of a Bootstrap 5 dropdown. The problem lies in the discrepancy between the button width and the menu width. Although it may seem simple, I am having trouble resolving it as I ...

Personalized Svelte interface Slider tag

I am trying to customize the label of a smui/slider in a tick marks and discrete slider. While I found instructions on how to do this using material web components at https://github.com/material-components/material-components-web/tree/v13.0.0/packages/mdc- ...

Angular - Transform calendar dates to a lively green upon initial popup activation

I'm looking to customize my calendar so that all the dates in my list have a green background when the calendar is opened. ngOnInit(): void { this.roomService.getReservableDatesFromRoom(room.roomName).subscribe(data => { for (let i = 0; i ...

Retrieving a numerical value from a string using Javascript or JQuery

Here is an example string: "example example-5 amount-10 example direction-left" Is there a way to extract the number following "amount-", and the text immediately after "direction-" in this string? ...

Retrieving Blocked Images with Selenium: A Step-by-Step Guide

HTML: <html> <head> <body onload="document.getElementById('a').style.display='block';"> <div id="a" align="center" onclick="document.location.reload();" style="display: block; cursor: pointer;"> <img width="9 ...

Parsley JS - Personalized Validation for Ensuring selected Items meet Minimum Value Requirements

Is it possible to validate a form so that at least 5 select boxes are set to Yes? If there are fewer than 5, the form should not submit and display an error message. I believe a custom validator is needed for this task. To see a complete example, check ou ...

Retrieve JSON data from an HTTP request using Node.JS

Hi there, I'm struggling with the Node.js HTTPS request. Basically, I send a request to a server and it responds with a JSON message that I need to parse and save in a variable so I can use it in other functions. let obj=JSON.parse(response); return ...

The process of setting up React in the terminal becomes tricky when the VS code editor is directing to a non-existent path

Issue with VS Code editor not recognizing existing path Recently attempted to install React using the npx command in the terminal, following steps from various tutorials on YouTube. Despite trying all suggested methods, the installation didn't succee ...

Guidelines for choosing a single integer from a collection of integers and floating-point numbers that have been extracted from a string

In my code, I have a set of doubles and ints that I parsed named gradeList. This data will be passed to a constructor. The grade list looks like this: "5 - 90 85 95.5 77.5 88" The '5' is an integer but the rest should be double values. My parsing ...

What could be the reason for my jQuery focusout (or blur) event failing to trigger?

On the jsfiddle link provided, the HTML code at the end section looks like this: <input type="text" id="BLAboxPaymentAmount" value="2"> </br> <input type="text" id="BLAboxSection5Total" value="3"> Below that is the jQuery code snippet: ...

What is the best way to display the arrows on a sorted table based on the sorting order in Angular?

I need assistance with sorting a table either from largest to smallest or alphabetically. Here is the HTML code of the section I'm trying to sort: <tr> <th scope="col" [appSort]="dataList" data-order ...

Is it possible to extract elements from a single list and insert them onto various pages?

Currently, I am retrieving items from a list using an ajax call. After constructing the HTML content, I insert these items onto a page. Now, I want to extract the same items and display them on another page with a different style. Is there a method to conn ...