Calculate the sum of arrays within an array (matrix) by adding the elements

What is the best way to calculate the vertical sum of data in an array of arrays?

arrayOfArrays = [{
    label: 'First Value',
    data: [1, 2, 3, 4, 5, 6, 7, 8]
  },
  {
    label: 'Second Value',
    data: [1, 2, 3, 4, 5, 6, 7, 8]
  },
  {
    label: 'Third Value',
    data: [1, 2, 3, 4, 5, 6, 7, 8]
  }
];

var result = arrayOfArrays.reduce(function(accumulatedArray, currentArray) {
  return accumulatedArray.data.map(function(value, index) {
    return value + currentArray.data[index];
  }, 0);
});

console.log(result)

The expected output is the vertical sum of arrays. [3,6,9,12,15,18,21,24]

An issue has been identified where array1 always returns as undefined.

Answer №1

Your code is almost correct but has one issue.

You are looping through the accumulator, which will result in an array of numbers in the second iteration. Instead, loop over array2 or the current item.

The purpose of using .reduce is to maintain the same structure for all iterations. If you do not provide a default value for the accumulator, the first iteration will be of type

Array<{ label: string, data: Array<number>}>
and the second iteration will just be Array<number>. To avoid this inconsistency, pass an empty array as the default value. This way, the calculation won't break when accessing array[n], as it will default to 0.

Therefore, your calculation should be:

value + (array1[index] || 0)

Here's a sample code snippet:

arrayOfArrays = [{
    label: 'First Value',
    data: [1, 2, 3, 4, 5, 6, 7, 8]
  },
  {
    label: 'Second Value',
    data: [1, 2, 3, 4, 5, 6, 7, 8]
  },
  {
    label: 'Third Value',
    data: [1, 2, 3, 4, 5, 6, 7, 8]
  }
];

var result = arrayOfArrays.reduce(function(array1, array2) {
  return array2.data.map(function(value, index) {
    return value + (array1[index] || 0);
  }, 0);
}, []);

console.log(result)

Answer №2

To utilize the index/key within the context of a map, simply incorporate it into the previous value.

const arrayData = [{name:'First Item', values:[1,2,3,4,5,6,7,8]},{name:'Second Item', values:[1,2,3,4,5,6,7,8]},{name:'Third Item', values:[1,2,3,4,5,6,7,8]}];
const result = arrayData.reduce((accumulator, current) => (current.values.map((item, key) => {accumulator[key] = accumulator[key] ? accumulator[key] += item : item}), accumulator), [])
console.log(result)

Answer №3

It appears you may have misunderstood how to use the reduce function. Here's an alternative solution using a for loop:

arrayOfArrays = [{
label:'First Value', data:[1,2,3,4,5,6,7,8]},
{label:'Second Value', data:[1,2,3,4,5,6,7,8]},
{label:'Third Value', data:[1,2,3,4,5,6,7,8]}
];
const newArr = [];

for(let x = 0; x < arrayOfArrays[0].length; x++){
newArr.push(arrayOfArrays[0].data[x]+arrayOfArrays[1].data[x]+arrayOfArrays[2].data[x])
}
console.log(newArr); // output new array

Answer №4

To simplify arrays, you can iterate through the array of objects and add the data property to a new array. Then, utilize reduce/map methods on the flattened data:

arrayOfArrays = [
  {label:'First Value', data:[1,2,3,4,5,6,7,8]},
  {label:'Second Value', data:[1,2,3,4,5,6,7,8]},
  {label:'Third Value', data:[1,2,3,4,5,6,7,8]}
];

var data = [];

arrayOfArrays.forEach((item)=> {
    data.push(item.data)
})

var sum = (result, arr) => result.map((val, index) => arr[index] + val);
var output = data.reduce(sum);

console.log(output);

This will produce the following output:

[3, 6, 9, 12, 15, 18, 21, 24]

View working example

Answer №5

If all arrays have the same length, you can implement the following solution:

arrayOfArrays = [{
    label: 'First Value',
    data: [1, 2, 3, 4, 5, 6, 7, 8]
},
{
    label: 'Second Value',
    data: [1, 2, 3, 4, 5, 6, 7, 8]
},
{
    label: 'Third Value',
    data: [1, 2, 3, 4, 5, 6, 7, 8]
}
];

let out = arrayOfArrays.reduce((acc, {data}) => acc.map((e, i) => e + data[i]), new Array(8).fill(0));

console.log(out)

The mistake in your code is passing the wrong accumulator parameter, it should be an array and placed within the reduce function rather than the map function.

var result = arrayOfArrays.reduce(function (array1, array2) {
    return array1.map(function (value, index) {
        return value + array2.data[index];
    });
}, Array(8).fill(0));

Answer №6

This is one way to approach the problem:

  1. Create a helper function called transport:

    const transport = (arr) => arr[0].map((col, i) => arr.map(row => row[i]));
    
  2. Prepare the matrix data:

    const matrix = arrayOfArrays.map(el => el.data)
    
  3. Finally, solve the task easily:

    const res = transport(matrix).map(arr => arr.reduce((x, y) => x + y))
    // > (8) [3, 6, 9, 12, 15, 18, 21, 24]
    

Answer №7

If you ever find yourself in need of transforming or manipulating values later on, function generators can be quite useful. They allow you to iterate through the values without having to deal with the entire result set at once.

The approach taken in this scenario involves using a function generator with the following logic:

  • Find the array with the longest length (assuming the lengths may vary).
  • Retrieve all elements located at index i from 0 to the length of the longest array, and then calculate their sum.

arrayOfArrays = [{
    label: 'First Value',
    data: [1, 2, 3, 4, 5, 6, 7, 8]
  },
  {
    label: 'Second Value',
    data: [1, 2, 3, 4, 5, 6, 7, 8]
  },
  {
    label: 'Third Value',
    data: [1, 2, 3, 4, 5, 6, 7, 8]
  }
];

/**
  Sums elements of arrays inside the array vertically.
*/
function* sumVertically(arr) {
  // Find the length of the longest array.
  const longestArrayLength = arr.sort(({length: l1}, {length: l2}) => l1 - l2)[0].length;
  // Grab all elements at index [i] from each array, add them up, and yield the sum.
  for (let i = 0; i < longestArrayLength; i++) yield arr.map(e => e[i]).reduce((a,b) => a + b, 0);
}

const result = [...sumVertically(arrayOfArrays.map(i => i.data))];

console.log(result);

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

Retrieve data from the following fields: {"attending":0,"eventid":1,"userid":1} using PHP

After receiving an array from JAVA and using print_r($_POST), I have tried various methods to extract data but with no success. The format of the array is as follows: {"attending":0,"eventid":1,"userid":1} I've attempted different approaches found o ...

Creating a unique data attribute in Alpine.js - A step-by-step guide

I am looking to establish a custom attribute and modify the value when clicked. This is my current setup: <div x-data="{ colorred = true }"> <div @click="colorred = !colorred">set red state</div> </div> I ...

To encounter an "undefined" response in the following route of an express application, utilize the next('route') function

const express = require('express') const app = express() app.get('/user/:uid', (req, res, next) => { if (req.params.uid === 'lai9fox') next('route') else next() }, (req, res, next) => { res.send(`<h1& ...

The issue of JQuery $(this) malfunctioning when used within a function parameter

Encountering an issue with the code snippet below: $(".countdown").circularCountdown({ startDate:$(this).attr('data-start'), endDate:$(this).attr('data-end'), timeZone:$(this).attr("timezone") }); On the contrary, the co ...

Guide on connecting various information to a jquery element through .data() within a custom plugin

I have come across a problem with my two plugins $.fn.expect = function (expectation) { return this.each(function () { $(this).data('expectation', expectation); }); } $.fn.isExpected = function () { return $(this).dat ...

PhantomJS in Python Selenium fails to retrieve source code after element click

View the code here import webdriver from selenium driver = webdriver.PhantomJS() driver.get("http://www.metasozluk.com/?r=girdi/goster&g=298794") driver.page_source # The result is a full HTML page. driver.find_element_by_css_selector(".entry-list-c ...

Select an <li> element from div1 and move it to div2 when a button is clicked

Even though I have experience with JavaScript, I am struggling to figure out a simple task. Here is the list of items I need help with: <div id="left-side"> <ul> <li><div>Item 1</div></li> <li> ...

Comparing two datetime objects with time zone offsets in JavaScript: How to determine if one is greater than or less than the other?

So I'm faced with a situation where I need to compare two dates where the first date is 05.01.2008 6:00 +5:00 and the second date is 05.01.2008 7:00 +5:00 I'm struggling to find a way to convert these datetimeoffsets into a specific forma ...

Hide the popup menu when the user clicks outside of it

I am presenting the following code <!DOCTYPE html> <html> <head> <title>GalacticCraft</title> <link rel="stylesheet" type="text/css" href="style.css" /> <link rel="shortcut icon" type="image/png" href="fa ...

Error: The function keytar.setPassword cannot be executed due to a TypeError

I am experiencing issues when trying to save a password using keytar.js. Every function from keytar is giving me an error. Just for reference, the library is properly installed and the functions are present (I verified this with console.log) and they work ...

Display real-time information fetched from sessionStorage (in JSON format) on a Listview widget

In my session, I have the following JSON data stored: Prescription: [{"medID":"id1","medName":"name1","medQty":"qty1","medDirec":"Directions1"}, {"medID":"id2","medName":"name2","medQty":"qty2","medDirec":"Directions2"}] I am looking to automatically dis ...

Contrast between utilizing a WebApp that connects to an API and one that relies on backend

Whenever I develop simple web applications, I often begin by setting up a nodeJS backend, usually creating an API server with ExpressJS. When specific routes are accessed, the server responds by dynamically rendering HTML from EJS based on the current conn ...

Ensure the video frame stretches to fit the full width

I am struggling to make my video frame fill the entire width of the screen. Even though I have tried using CSS, the video container does not stretch to the full width as expected. https://i.sstatic.net/kxyE0.png How can I ensure that the video plays acro ...

A pop-up box appears when hovering over a radio button

There are three radio button options available: None Float Left Float Right When the user hovers over the radio button, I want to show a preview of the div. <asp:radiobuttonlist runat="server" id="rbl" repeatdirection="Horizontal"> <asp:li ...

Is it necessary for services in Domain Driven Design to have knowledge of other services, or should they be aware of multiple repositories

As I work on developing a backend application, my focus is on implementing the Domain Driven Design. However, there's a particular question I have regarding the data structure that requires some clarification. Database Configuration Users Id ( ...

Executing a php function upon onchange event triggered by CKEditor

My task involves invoking a PHP function when I suspect it is being triggered by an ajax call. Utilizing ckeditor, I aim to detect any keyboard activity and believe that using onchange will serve this purpose. Subsequently, I plan to execute a function t ...

Accessing a JSON file from a nearby location using JavaScript

I am currently working on an artistic project based on weather data, which will be hosted locally with the JSON file updating via FTP synchronization. This means that the JSON file will be sourced from the same computer where it is stored. The code snippet ...

What's the best way to organize array data for a cleaner look?

Here's a method that I've been using: private function formatCliendCardData($data) { $formatedData = array(); $formatedData['first_name'] = trim($data['name']); $formatedData['last_name'] = trim($data[& ...

Transfer information from .gs (Google Apps Script) to a variable inside a <script> tag in an HTML document

[ {"id":1,"label":"Node 2"}, {"id":2,"label":"Node 3"}, {"id":3,"label":"Node 4"}, {"id":4,"label":"Node 5"} ] Hello there! The function getArray() in the code snippet above is returning the specified string ↑. I need help connecting this data w ...

Creating a component in Vue to showcase Axios, based on a straightforward example from the documentation

I apologize in advance for what may seem like a trivial question, but I assure you that I have put in a considerable amount of effort to solve this problem without success. In my appService.js file, I am making an API call as follows: import axios from &a ...