What is the best way to calculate the total of elements from multiple arrays of various lengths using Javascript?

Is there a way to modify the code below to allow for adding an arbitrary number of arrays as arguments? For instance, how can I adjust it so that ([1, 2, 3], [4, 5], [6]) would result in an array of [11, 7, 3]?

function addArrays(...arrays) {
  let result = new Array(Math.max(...arrays.map(arr => arr.length))).fill(0);

  arrays.forEach((arr) => {
    arr.forEach((num, index) => {
      result[index] += num;
    });
  });

  return result;
}

Answer №1

Instead of manually creating two separate array variables, you can utilize a nested array and loop through it dynamically.

To achieve this, utilize arrays.map() to retrieve all the lengths for calculating the maximum length, and then use arrays.reduce() to add up the elements in each array.

const combineArrays = (...arrays) => {
  let combinedArray = [];
  let maxLength = Math.max(...arrays.map(a => a.length));
  for (let i = 0; i < maxLength; i++) {
    combinedArray.push(arrays.reduce((sum, arr) => sum + (arr[i] || 0), 0));
  }
  return combinedArray
}

console.log(combineArrays([1, 2, 3], [4, 5], [6]));

Answer №2

You have the ability to utilize the arguments object within a function.

arguments serves as an Array-like object that can be accessed inside functions, containing the values of the arguments passed into that particular function.

const combineArrays = function () {
  const inputs = [...arguments];
  const maxLength = Math.max(...inputs.map((item) => item.length));
  const result = [];
  for (let i = 0; i < maxLength; i ++) {
    result.push(inputs.reduce((acc, cur) => acc + (cur[i] || 0), 0));
  }
  return result;
};

console.log(combineArrays([1,2,3], [4,5], [6]));

Answer №3

Here is the solution:

function combineArrays(...arrays) {
  let result = [];
  let maxLength = 0;
  
  arrays.forEach((array) => {
    maxLength = Math.max(maxLength, array.length);
  });
  
  for (let i = 0; i < maxLength; i++) {
    result[i] = 0;
    
    for (let j = 0; j < arrays.length; j++) {
      if (arrays[j][i]) {
        result[i] += arrays[j][i];
      }
    }
  }
  
  return result;
}

console.log(combineArrays([1, 2, 3], [4, 5], [6]));

The output will be: [11, 7, 3]

Answer №4

Utilize the rest parameter syntax to receive an unlimited number of arguments. Arrange the main array in descending order based on length. Employ destructuring assignment to separate the first array from the rest of the arrays. Lastly, utilize Array.prototype.map() to iterate through the first array, which is the largest one, and use Array.prototype.reduce() method to calculate the total sum.

const mergeArrays = (...ar) => {
  ar.sort((x, y) => y.length - x.length);
  const [first, ...br] = ar;
  return first.map(
    (x, i) => x + br.reduce((p, c) => (i < c.length ? c[i] + p : p), 0)
  );
};

console.log(mergeArrays([1, 2, 3], [4, 5], [6]));

Answer №5

If you want to avoid using a for loop where you have to determine the length of each array in advance, consider utilizing a different approach like a while loop.

You can increment using a placeholder variable, reset it for each array, and establish the termination condition for the loop as arr[i] === null.

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

Unable to retrieve a substring value in Angular using Typescript

html <p> <input type="text" maxlength="40" (input)="recipientReference = deleteSpacing(recipientReference)" [(ngModel)]="recipientReference" style="width: 30vw; padding: 5px;border: 1px solid;border ...

Transforming an array from two dimensions to one dimension using PHP

Here is an example of an array: array(1) { ["foo"]=> array(2) { [1]=> string(5) "abcde" [2]=> string(4) "pqrs" } } Now, I would like to transform it into the following format: array(2) { [1]=> string(5) "abcde" [ ...

Preventing the submission of form post values by using jQuery remote validation

     Within my form, I have incorporated two submit buttons (save & exit, next) and implemented remote email address duplication checks. Everything is functioning properly, however, upon submission of the form, I am unable to determine which specific s ...

Utilize jQuery to locate a specific value within a collapsible Bootstrap 4 table

Is it possible to use a Bootstrap 4 table inside a collapse? I need to search for a specific value in the table and if the value is found, I want to open the collapse and display the row containing that value. <div id="collapseStudents" class="collapse ...

I am interested in combining fabricjs with vue.js

I am currently exploring the integration of fabricjs with vue.js, but I have encountered some issues along the way. Below is a snippet of my code: var app = new Vue({ el: '#content_vue', data: { }, methods: { add_image: function() ...

Angular Bootstrap uibModal is failing to resolve attributes

Issue with Roles in AngularJS Bootstrap uiModel var modalInstance = $uibModal.open({ animation: $scope.animationsEnabled, templateUrl: 'myModalContent.html', controller: 'ModalInstanceCtrl', size: 100, resolve: { roles: f ...

Unable to delete component from an array (slice, Vue.js)

I'm currently working on implementing dynamic addition and removal of components in Vue.js. I've encountered an issue with the slice method, which is supposed to remove an element from an array by the provided index. To modify the array, I am us ...

The function SetInterval is invoked multiple times

I am currently working on developing a Tetris game and I have encountered a bug that affects the speed of the game. The issue arises when the function setInterval(move_tetris_part,interval_time); is called multiple times, resulting in an increased downward ...

Searching for client using mqtt.js in Angular2 with Typescript yields no results

I am facing a unique issue while trying to incorporate the mqtt.js library into Angular 2 using TypeScript. Below is my app.component.ts file: import { Component } from '@angular/core'; import * as mqtt from 'mqtt'; @Component({ sel ...

Forgetting variable after utilizing jQuery ajax in php

I am facing an issue with PHP not retaining variables when I use jQuery ajax. Can you provide me with guidance on how to ensure that it remembers its variables? Attached at the bottom of this message are the code files. Firstly, question.php sends a quest ...

Utilize another function located within a JavaScript module

I'm encountering an issue while trying to reference the getJSONS function from another function within the script. The error message I'm seeing is (node:5857) UnhandledPromiseRejectionWarning: TypeError: this.getJSONS is not a function. How can ...

Retrieve the content entered in a form text field without needing to officially submit the form

Is it possible to submit the text box value (partnumber) as a query string in a hyperlink without submitting the form itself? I have been trying to achieve this by using document.getElementById("partnumber").value but keep getting an error "Object Required ...

Troubles with setting up node modules in a Windows 10 environment

I'm encountering difficulties when trying to install modules on my Windows 10 laptop after setting up Node.js from scratch. Since it's my personal computer, I have complete control over the system. Despite searching through various online forum ...

Tips for creating an Enumerable 'similarity' search using linq.js

I have a JSON array that looks like this: [ { "_Id": "0001", "_PatentId": "0000", "_Text": "Employee", "_Value": "employee", "_PermissionLevel": 55 }, { "_Id": "0002", "_PatentId": "0000", "_Text": "Employees" ...

Unable to integrate bower with gulp for automation

I am trying to get gulp to run the installation of all files listed in my bower.json. However, despite writing the code below, it is not working and I'm not seeing any errors. What could be causing this issue? var gulp = require("gulp"); var bower = ...

Experiencing difficulty retrieving individual :id information from a list in MEAN stack

**I'm experiencing issues retrieving a single :id from a list as the data returned is not what I expected... ** GET /article/5b0be8829f734a4e580a43c5 401 3.845 ms - 99 ===> response from my get request my api ===> var express = require ...

Ways to stop Google Places API from generating outcomes from a particular country

After carefully reviewing the entire documentation at https://developers.google.com/maps/documentation/javascript/reference/places-service#LocationRestriction, I am still unable to find a solution to my problem. I have successfully limited Google autocomp ...

How can I update the color of a list item when it is clicked within a foreach loop using knockout js?

Currently, I am encountering an issue with changing the color when a user clicks on a list item using the latest version of knockout js. My goal is to change the color of a list item when it is clicked and maintain that color until another item is clicked, ...

Flask is having trouble loading images within the static directory

I am facing an issue with loading two images in my HTML when the 'next' button is clicked. Initially, everything was working fine before I integrated the front end with Flask. The CSS and JS files are functioning properly, but the images are not ...

What is the method for assigning 'selective-input' to a form field in Angular?

I am using Angular and have a form input field that is meant to be filled with numbers only. Is there a way to prevent any characters other than numbers from being entered into the form? I want the form to behave as if only integer keys on the keyboard ar ...