What is the best way to combine elements at matching indexes from an array of arrays into a unified array?

Suppose I have an array of arrays structured as follows:

[
  [0, 1, 3],
  [2, 4, 6],
  [5, 5, 7],
  [10, 0, 3]
]

Is there a way to create a new array that calculates the sum of all values at each index position within the inner arrays using JavaScript? For the given example, the result would be: [17, 10, 19]. I need a solution that will work regardless of the length of the inner arrays. I believe it may involve a combination of map and for-of loops, or maybe reduce method, but I am struggling to understand the implementation. Despite my search efforts, I have not found any examples that precisely match this scenario.

Answer №1

To achieve this, you can utilize the Array.prototype.reduce() method in conjunction with Array.prototype.forEach().

var array = [
        [0, 1, 3],
        [2, 4, 6],
        [5, 5, 7],
        [10, 0, 3]
    ],
    result = array.reduce(function (r, a) {
        a.forEach(function (b, i) {
            r[i] = (r[i] || 0) + b;
        });
        return r;
    }, []);
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

A more concise approach involves using a map within the reduce function for array reduction.

var array = [[0, 1, 3], [2, 4, 6], [5, 5, 7], [10, 0, 3]],
    result = array.reduce((r, a) => a.map((b, i) => (r[i] || 0) + b), []);
    
console.log(result);

Answer №2

Utilizing Lodash 4:

function calculate_column_sum(data) {
  return _.map(_.unzip(data), _.sum);
}

var result = calculate_column_sum([
  [1, 2],
  [4, 8, 16],
  [32]
]);

console.log(JSON.stringify(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

For earlier versions of Lodash and some notes

Lodash 4 has altered the functionality of _.unzipWith, where now the iteratee receives all values as spread arguments simultaneously, making it incompatible with using the reducer style _.add. In Lodash 3, the following example functions correctly:

function calculate_column_sum(data) {
  return _.unzipWith(data, _.add);
}

var result = calculate_column_sum([
  [1, 2],
  [4, 8, 16],
  [32],
]);

console.log(JSON.stringify(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js></script>

_.unzipWith will place undefineds in rows shorter than others, while _.sum considers undefined values as 0 (in Lodash 3).

If your data includes undefined and null items and you wish to treat them as 0, you can use the following:

function calculate_column_sum_safe(data) {
  return _.map(_.unzip(data), _.sum);
}

function calculate_column_sum(data) {
  return _.unzipWith(data, _.add);
}

console.log(calculate_column_sum_safe([[undefined]])); // [0]
console.log(calculate_column_sum([[undefined]]));      // [undefined]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js</script>

This code snippet is compatible with Lodash 3; unfortunately, finding a clean way to handle undefined as 0 in Lodash 4 proves challenging as _.sum([undefined]) === undefined

Answer №3

Short code snippet using ES6, utilizing map and reduce

const matrix = [ [2, 4, 6], [1, 3, 5], [7, 8, 9] ];

const result = matrix[0].map((_, i) => matrix.reduce((prev, _, j) => prev + matrix[j][i], 0));

console.log(result);

Answer №4

To efficiently handle nested arrays with equal lengths, concatenation and reduction techniques can be utilized.

    function calculateTotal (arr) {
        var length = arr[0].length;
       return [].concat.apply([],arr)  //flatten the array
                .reduce( function(arr, val, ind){ //loop over and create a new array
                    var i = ind%length;  //get the column
                    arr[i] = (arr[i] || 0) + val; //update total for column
                    return arr;  //return the updated array
                }, []);  //the new array used by reduce
    }
    
    var arr = [
      [2, 3, 6],
      [1, 4, 8],
      [7, 9, 2],
      [12, 10, 14]
    ];
    console.log(calculateTotal(arr));  //[22, 26, 30]

Answer №5

Given that the array is static as displayed.

a = [
      [0, 1, 3],
      [2, 4, 6],
      [5, 5, 7],
      [10, 0, 3]
    ]

b = []
     
for(i = 0; i < a[0].length; i++){
  count = 0
  for(j = 0; j < a.length; j++){
     count += a[j][i]
   }
   b.push(count)
}
console.log(b)

Answer №6

No responses so far using the for ... of syntax mentioned in the initial question.
I chose to implement a solution with conditional statements for arrays of varying lengths.

var arr = [
  [0, 1, 3],
  [2, 4, 6],
  [5, 5, 7],
  [10, 0, 3]
];
index = 0;
resultArr = []
for (const innerArr of arr) {
  idx = 0;
  for (const numVal of innerArr) {
    if (idx == resultArr.length) resultArr.push(numVal)
    else resultArr[idx] += numVal
    idx++;
  }
  index++;
}
console.log(resultArr);

Indeed, in this scenario, utilizing the traditional for loop is more suitable than for ... of.
The code snippet below demonstrates the use of a conditional (ternary) operator.

var arr = [
  [0, 1, 3],
  [2, 4, 6],
  [5, 5, 7],
  [10, 0, 3]
];

resultArr = [];
for (count = 0; count < arr.length; count++) {
  for (jCount = 0; jCount < arr[count].length; jCount++) {
    jCount==resultArr.length ? resultArr.push(arr[count][jCount]) : resultArr[jCount]+=arr[count][jCount]
  }
}

console.log(resultArr);

An innovative approach employing maps and reductions to sum elements from arrays of different sizes.

var arraySamples = [
  [0],
  [2, 4],
  [5, 5, 7, 10, 20, 30],
  [10, 0]
];
bArr = Array(arraySamples.reduce((a, b) => Math.max(a, b.length), 0)).fill(0);
finalResult = arraySamples.reduce((res, ar) => bArr.map((_, ind) => (ar[ind] || 0) + (res[ind] || 0)), []);

console.log(finalResult);

Answer №7

let arr = [
  [1, 2, 4],
  [3, 5, 8],
  [6, 6, 9],
  [11, 1, 4]
]   

arr.map( element => element.reduce( (accumulator, value)=> accumulator += value, 0 ) )
//output-> [7, 16, 21, 16]

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

Having trouble choosing an option from the dropdown menu in bootstrap

I'm experiencing an issue with a bootstrap dropdown that I created. I am unable to select an item from it. The code is shown below: var aos = ''; $('.dropdown-item').click(function(event) { event.preventDefault(); // Prevents ...

Unable to retrieve information from JSON file utilizing AngularJS version 1.6

I'm having trouble retrieving data from my JSON file using AngularJs 1.6 myApp.controller("homeCtrl", function($scope, $http) { $scope.Data = []; var getJsonData = function() { $http.get('contactlist.json').then(func ...

Transitioning the height of a Vue component when switching routes

I've been struggling to implement a transition slide effect on my hero section. The height of the hero is set to 100vh on the homepage and half of that on other pages. Despite trying various methods, I haven't been able to get it working properly ...

Setting the state of a nested array within an array of objects in React

this is the current state of my app this.state = { notifications: [{ from: { id: someid, name: somename }, message: [somemessage] }, {..}, {..}, ] } If a n ...

Registering dynamic modules within a nested module structure - Vuex

As stated in the Vuex documentation, a nested module can be dynamically registered like this: store.registerModule(['nested', 'myModule'], { // ... }) To access this state, you would use store.state.nested.myModule My question is h ...

Looking to retrieve an element from an array of objects based on consecutive object properties, I have a specific value to search for

const levels = [ { indexId: 'A', level: 1, name: 'A', parent: '0', }, { indexId: 'A-A1', level: 2, name: 'A1', parent: 'A', }, { ...

What is the best way to extract information from a JavaScript page when the content is identified by a reference?

If you're looking for the website, you can visit . It's primarily in Chinese, but that may not be relevant to the topic at hand. Currently, I am able to extract all the content from this page and now I'm interested in moving on to the next ...

Javascript Code for toggling the visibility of a panel

I need help with a JavaScript code that can show or hide a panel depending on the data in a grid. If the grid has data, the panel should be displayed, but if the grid is empty, the panel should be hidden. I attempted to use the following code, but it did ...

The error "Call to a member function exports() on array" occurs when attempting to use the

As I attempt to send an array of values to the jobExport() collection, I encounter an error stating Call to a member function jobsExport() on array. I comprehend the necessity for the collection to be populated with modal collection value. However, my goal ...

Every time I try to request something on my localhost, NextJS console throws a TypeError, saying it cannot read the properties of undefined, specifically '_owner'

Update: I've noticed that these errors only appear in Chrome, while other browsers do not show them. Recently, I created a simple NextJS project by following a couple of tutorials, which also includes TypeScript. However, after running npm run dev, I ...

Comparing PHP's STRCHR with the equivalent function in JavaScript

Does anyone know if there is a similar function in JavaScript to strchr in PHP? I could use some assistance. Thank you! ...

Resolving Typescript jQuery AJAX Navigation Problem

Hello dear Earthlings, The code snippet below is currently implemented on my website brianjenkins94.me for handling basic navigation functionalities. After some recent changes, I encountered an issue with the #nav.on("click") event handler not working as ...

Tips for Creating a Smooth Slide-Down Effect in Your Navbar Menu

Desired Outcome - My aim was to create a smooth slide down effect for the navbar after scrolling. While I managed to achieve this, I am encountering an issue. The Issue - Whenever I scroll back up to the top, the navbar becomes sticky without any transiti ...

Can child components forward specific events to their parent component?

I created a basic component that triggers events whenever a button is clicked. InnerComponent.vue <template> <v-btn @click="emit('something-happened')">Click me</v-btn> </template> <script setup lang=" ...

Unable to retrieve basic profile data from LinkedIn Members using their email ID unless they are signed in

I am struggling to retrieve the basic profile details of Linkedin Members using their email ID. Despite my efforts, I haven't been able to find relevant information in the documentation. My attempt involved creating an app, initializing the JavaScrip ...

Is there a way to automatically increase a value by clicking on it?

Check out this code snippet I'm working with: let funds = document.createElement('funds') funds.style.color = 'green' funds.style.textAlign = 'center' funds.style.fontSize = '50px' funds.style.backgroundCol ...

Optimize and compress your Angular 4 code

Currently, I am working with the Asp Core +Angular 4 template and using webpack in Visual Studio 2017. After publishing my app, when I check the content of ClientApp/dist/main-server.js, I notice that it is not minified or uglified. It looks something like ...

Ensure that the loop is fully executed before proceeding with any additional code

Check out this code snippet I've been developing: let arrayB = []; for (let index = 0; index < res.length; index++) { let fooFound = false; const dynamicFoo = require(`./modules/${res[index]}`); rest.get(Routes.applicationCommands("BLA ...

Unlocking the secret path to reach an untraceable object nested within another object using

After using php's json_encode() function, I received a string that looks like this: [ { "key1":"value1", "key2":"value2", "key3":"value3" }, { "key1":"value1", "key2":"value2", "key3":"value3" } ] To convert the string into a J ...

When a specific item is selected from a drop-down menu, text boxes and drop-downs will dynamically appear and change

In the current version of my code, there is a single drop-down menu with three options for the user to select from. If "Complete" is chosen, a text box should appear. If "Abandon" or "Transfer" is selected, a separate drop-down menu needs to be displayed. ...