Adding arrays in javascript

Consider the following arrays:

// The goal is to calculate these arrays against each other.
var a = [1,2,3]
var b = [1,2,3]
var c = [3,4,5]
// ->
var result = [5, 8, 11]

While there are methods available to calculate two arrays at a time, how can we sum n arrays together?

Array.prototype.Sum = function (arr) {
    var s = [];
    if (arr != null && this.length == arr.length) {
        for (var i = 0; i < arr.length; i++) {
            var c = this[i] + arr[i]
            s.push(c);
        }
    }
    return s;
}

Answer №1

Suppose

let arrays = [
    [1,2,3],
    [1,2,3],
    [3,4,5]
];

Utilizing the Sum function with EcmaScript 5 array methods,

let result = arrays.reduce(function(arr1, arr2){
    return arr1.Sum(arr2);
});

Alternatively, you can avoid extending Array.prototype and opt for something like this (ES5)

let result = arrays.reduce(function(arr1, arr2) {
    return arr1.map(function(num, index){
        return num+arr2[index];
    });
});

Or, simplify using EcmaScript 6 arrow functions,

let result = arrays.reduce(
    (arr1, arr2) => arr1.map(
        (num, index) => num+arr2[index]
    )
);

Answer №2

Here is a simple ECMAScript 3 solution:

var arrays = [
    [1, 2, 3],
    [1, 2, 3],
    [3, 4, 5]
];

function sum() {
  var total = [];
  for(var i = 0; i < arguments.length; ++i) {
    for(var j = 0; j < arguments[i].length; ++j)
      total[j] = (total[j] || 0) + arguments[i][j];
  } return total;
}

sum.apply(this, arrays);              // [ 5, 8, 11 ]
sum(arrays[0], arrays[1], arrays[2]); // [ 5, 8, 11 ]

Answer №3

This unique function allows you to add multiple arrays without the need to nest them within another array...

Furthermore, it is compatible with older browsers.

function CombineArrays(){
  if (arguments.length == 0){
    return null;
  }
  var sum = arguments[0];
  for(var j = 1; j < arguments.length; j++) {
     var arr = arguments[j];
     for (var i = 0; i < arr.length; i++) {
         sum[i] = sum[i] + arr[i];
     }
  }
  return sum;
}

Simply use CombineArrays(a, b) or CombineArrays(a, b, c) ...

If desired, this function can also be placed in your prototype (with modifications to utilize this for in-place summation).

Answer №4

Function a adds b and then adds c;

Executing this should yield the desired 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

Having trouble deciphering the undefined jquery scroll at the top

I have been attempting to resolve this error without success, so I am turning to you with my specific issue. I am using a jQuery scroll feature that navigates to the hashtags in the menu. When it reaches the targeted hashtags, the menu item color should ch ...

Eliminating null values from a multidimensional array

Is there a way to remove the array elements cctype, cctypologycode, and amount if they are empty? What would be the most efficient approach? { "ccInput": [ { "designSummaryId": 6, "CCType": "A", "CCTypologyCode": "A", "Amount ...

What is the best way to verify if an array includes specific values with supertest?

Imagine a scenario where I have the following array in response to tests: array = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' ] I wan ...

Waiting for an Element to Become Visible in Selenium-Webdriver Using Javascript

When using selenium-webdriver (api docs here), how can you ensure that an element is visible before proceeding? Within a set of custom testing helpers, there are two functions provided. The first function successfully waits for an element to exist, howeve ...

Encountering a critical issue with Angular 12: FATAL ERROR - The mark-compacts are not working effectively near the heap limit, leading to an allocation failure due

After upgrading my Angular application from version 8 to 12, I encountered an issue. Previously, when I ran ng serve, the application would start the server without any errors. However, after updating to v12, I started receiving an error when I attempted t ...

Form a combination of distinct elements from an array of unique types in typescript

I am wondering if it is possible to define an array of unique types based on a union of those types. Let's say I have the following type Value: type Value = string | number Then, I attempted to create a type called Values like this: type Values = ...

Data Transformation: Apply Regular Expression Pattern to Individual Elements in an Array

Looking to iterate through an array ["NJK","NST","NIR"] in dataweave and match each element with the pattern /^N.*[^1]$/ (starting with N and not ending with 1), returning 'true' if any element satisfies this condition. How can I achieve this ite ...

Challenges encountered when using setState to assign values

Just started using React and running into an issue with updating state when changes are made to a Textfield. I'm working with a functional component where the initial state is set using useState. I feel like I might be overlooking something simple... ...

Introduction to Angular controller binding for beginners

I'm currently going through this tutorial : http://www.youtube.com/watch?v=i9MHigUZKEM At 46:32 minutes into the tutorial, this is the code I have implemented so far : <html data-ng-app="demoApp"> <body data-ng-controller="SimpleControlle ...

IE9 encounters an error when using jQuery's .remove() function

While testing my website in IE9 using Firebug Lite, I encountered an issue. When attempting to run a basic command to remove a div, I received an error saying "TypeError: Object expected". The command I used was: $("#drag-hoverbox_you").remove(); Interes ...

I keep running into an issue whenever I attempt to import material ui icons and core - a frustrating error message pops up stating that the module cannot be found

[I keep encountering this error message when attempting to utilize @material-ui/core and icons] `import React from "react"; import "./Sidebar.CSS"; import SearchIcon from "@material-ui/icons/Search"; const Sidebar = () => { return ( <> ...

Navigating the Spine

Struggling to get routing to function properly in Backbone, I have tried my best but it still seems quite confusing. Here is a snippet of what I currently have: routes: { '' : 'home', 'home' ...

Guide to incorporating a simple animation into a component using Vue.js

As I explore the official Vue documentation on animation, I find myself puzzled about how to integrate the example provided on the Vue website: Vue.transition('fade', { css: false, enter: function (el, done) { // element is already inser ...

Having trouble with an AJAX request to display a template in Flask

Imagine having two radio buttons labeled 1 and 2, along with some text at the bottom of a webpage. Initially, the text value is set to -1 and no radio buttons are selected. If one of the radio buttons is clicked, the text value should change to either 1 or ...

Retrieve data from a different state within a Vue component

Within my application, I have set up 2 distinct routes: one for appointments and the other for doctors. Specifically in the doctors route, my goal is to have the parameters from a click event on the Book Now button (seen in image-1) dynamically replace the ...

Leveraging the power of the map function to cycle through two arrays

Right now in React, I am utilizing array.map(function(text,index){}) to loop through an array. But, how can I iterate through two arrays simultaneously using map? UPDATE var sentenceList = sentences.map(function(text,index){ return <ListGr ...

Using Next-Image Relative Paths can lead to 404 errors when being indexed by web crawlers

I have implemented next-image in my project, and all the images are hosted on Cloudinary. The images display correctly, but when I run a website analysis using tools like Screaming Frog, I receive numerous 404 errors. This is because the tools are looking ...

Trouble with Title Updating in Next.js and Tailwind CSS Project

I am currently facing an issue with the title of my website not updating, even though I am using next/Head and have included the title tag. "use client"; import Head from 'next/head'; import { BsFillMoonStarsFill } from 'react-ico ...

React.js and Visual Studio Code have recently been causing unexpected and massive "Module not found" errors

Everything was going smoothly with my project until I uploaded it to Github and then cloned it. Suddenly, I started encountering various "Module not found: Can't resolve..." import errors. For example: Module not found: Can't resolve './co ...

There seems to be an issue with the functionality of the operators in the Calculator Javascript

I'm currently working on a Javascript calculator project for FreeCodeCamp and encountering an issue with the code. Whenever I input an operator like "-", "+", "x", etc., the numbers in the history section start repeating themselves. For example, if I ...