Adding up the values of an array based on their position in Javascript

I came across a JavaScript array that looks like this:

var array1 = [ [1, 2, 3], [7, 9, 2], [6, 8, 1] ]

What I'm aiming for is to get the following output:

var array2 = [ 14, 19, 6 ]

array1[0] = 1 + 7 + 6
array1[1] = 2 + 9 + 8
array1[2] = 3 + 2 + 1

Is there a way to sum each element of an array based on its index?

Answer №1

If you're looking to consolidate arrays based on index, consider this solution:

const arr1 = [ [5, 3, 2], [10, 12, 9], [4, 6, 1] ];
const arr2 = [ [3, 5, 7], [8, 10, 2], [5, 3, 8] ];


function mergeByIndex(array) {
    return array.map((subArr) => {
        return array.reduce((acc, curr) => acc + curr[subArr] , 0 );
    });
}


mergeByIndex(arr1)
//[ 19, 21, 12 ]


mergeByIndex(arr2)
//[ 16, 18, 17 ]

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

Is it possible to align an entire column to the right in the Material UI Data Grid?

I'm currently exploring Material UI and grappling with a specific challenge. Is there a method within Material UI to create a Data Grid with two columns, one left-aligned and the other right-aligned? I've managed to align the headers as desired, ...

Creating a Dynamic Canvas Rendered to Fit Image Dimensions

I'm struggling with a piece of code that creates an SVG and then displays it on a canvas. Here is the Jsbin Link for reference: https://jsbin.com/lehajubihu/1/edit?html,output <!DOCTYPE html> <html> <head> <meta charset=&qu ...

Fill a form with jQuery and ajax data after it has been submitted

I'm working on a simple HTML form and I want to use Ajax to perform a lookup using a PHP file after entering data into the first field. The goal is to fetch information from an external source for the two remaining fields. <form method="post" acti ...

In order to activate the input switch in Next.Js, it is necessary to initiate a

Currently, I am working on implementing an on-off switch in Next.Js. To seek assistance, I referred to this helpful video tutorial: https://www.youtube.com/watch?v=1W3mAtAT7os&t=740s However, a recurring issue I face is that whenever the page reloads, ...

Efficient techniques for converting a list to a set in Python 2.7

Currently in my code, I am utilizing the following: im_set=set(map(tuple, im_list[0])) to convert a list into a set. However, this process is significantly slow. Are there any alternative methods without using map that can expedite this conversion? Here ...

I am experiencing an issue where the Javascript keydown event does not recognize the character "@" in the EDGE browser

Currently, I am developing a mentioning directive that displays a list of users when the user types in an input field (a div with contentEditable=true). The user can then insert the name of the desired user in a specific format. The list is supposed to be ...

Tips for providing support to a website without an internet connection

I am in the process of creating a sales platform for a grocery store that utilizes PHP/MySQL. I have come across some websites that are able to fully reload and function even without internet access. For instance, when I initially visited abc.com, everyth ...

Retrieve an array from a JSON object by accessing the corresponding key/value pair using the utility library underscore

I have a dataset in JSON format (as shown below) and I am attempting to use the _.where method to extract specific values from within the dataset. JSON File "data": [{ "singles_ranking": [116], "matches_lost": ["90"], "singles_high_rank": [79 ...

No children were located within the div element

Presently, I am attempting to disable an image for the initial element in each faqs div class in HTML. To achieve this, I am aiming to target the parent element of faqs and then navigate downwards to locate the initial list element using the following Java ...

Vue.js Google Places Autocomplete Plugin

I'm currently working on integrating Google Places Autocomplete with Vue.js. According to the API documentation, the Autocomplete class requires an inputField:HTMLInputElement as its first parameter, like shown in their example: autocomplete = new g ...

Turning off v-navigation-drawer for certain routes in Vue.js

I currently have a v-navigation-drawer implemented in my webpage using the code below in the App.vue file. However, I am looking to disable it on certain routes, such as the landing page: <v-app> <v-navigation-drawer id ="nav" persistent : ...

Using default language in Next.js internationalization: a step-by-step guide

I've been immersing myself in the Nextjs internationalization documentation for the past two days. My goal is to have support for two languages: en, fa. I also want to be able to switch between them with URLs structured like this: https://example.com ...

retrieving the file directory from a folder with the help of ajax

I am having trouble retrieving a list of files from a specific URL that lists files inside a folder: https://i.sstatic.net/VH22b.png In order to obtain this list of files using JavaScript, I have written the following code: $.ajax({ url: &ap ...

Different ways to notify a React/Next.js page that Dark Mode has been switched?

I am in the process of creating my first basic Next.js and Tailwind app. The app includes a fixed header and a sidebar with a button to toggle between dark and light modes. To achieve this, I'm utilizing next-theme along with Tailwind, which has been ...

Don't forget to expand or collapse

I'm struggling to make this work. My goal is to initially display 50 characters and show the rest when the "read more" button is clicked, and vice versa with "read less." Another problem I've noticed is that when I click the back browser button, ...

Only the first result is printed by mysql_fetch_array

Similar Query: Looping through mysql_fetch_array in PHP I am facing an issue with my join query where I try to print out multiple array results using a foreach loop. Despite having 801 results in the array, only the first result gets printed. If anyon ...

Load a form using ajax and submit it using jQuery

For a while now, I have been facing challenges in figuring out what's going wrong with my code. The issue arises when I try to submit a form using jQuery that was loaded through ajax. The form loads perfectly fine within a div after invoking the ajax ...

Terminate a remotely shared ngrok session that is forwarding a React application

My coworkers and I share an ngrok account while developing a React application using 'npx create-react-app' on UNIX-like systems. Occasionally, when trying to spin up an HTTP tunnel, I encounter the message: Your account '*****@*********.com ...

What is the easiest way to pass a chosen value to PHP?

My goal is to dynamically display photos based on the selected album without refreshing the entire page. Here is my current script: <script type="text/javascript"> function replaceContent(divName, contentS) { document.g ...

Error: Syntax mishap detected - Oh dear

Recently, I've been developing a small slideshow / public display for a client using the HTML5 Rock's Slideshow code. Everything was going smoothly until I encountered a DOM Exception 12 - an error related to CSS selectors. Strangely, I couldn&ap ...