Calculate the total of every pair of numbers within an array

Looking to calculate the sum of pairs of numbers from an array? Here's how to do it:

Numbers = [1,2,3,4,5,6....]

Sum of Pairs = [3,7,11,...]

Appreciate your help

Answer №1

Here is a solution you can implement:

let numbers = [5, 10, 15, 20, 25];

let counter = 0;
let result = numbers.reduce((accumulator, currentValue) => {
  if(counter === 0) {
    accumulator.push(currentValue);
    counter++;
  } else {
    accumulator[accumulator.length-1] += currentValue;
    counter = 0;
  }
  return accumulator;
}, []);

console.log(result);
.as-console-wrapper {min-height: 100%!important; top: 0}

Answer №2

Here's another method to achieve that:

const values = [10, 20, 30, 40, 50];

const oddNumbers = values.filter((value, index) => index%2 - 1);
const evenNumbers = values.filter((value, index) => index%2);
const finalResult = oddNumbers.map((val, idx) => val + (evenNumbers[idx] || 0));

console.log(finalResult);

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

Utilizing ThreeJS: Implementing a Sprite in Conjunction with the OculusRiftEffect

I am currently working on a project for the OculusRift using the OculusRiftEffect found at https://github.com/mrdoob/three.js/blob/master/examples/js/effects/OculusRiftEffect.js and incorporating Sprites into the design. However, I am facing an issue where ...

Using Javascript to place a form inside a table

When attempting to add a Form inside a Table, only the input tags are being inserted without the form tag itself. $(function () { var table = document.getElementById("transport"); var row = table.insertRow(0); var cell1 = row.insertCell(0); ...

The JSON output from the gapi (Google Analytics) array in PHP is not displaying any values

I've been utilizing the gapi class within a CodeIgniter website. The implementation I'm using is based on this resource, which returns an array that functions perfectly. To pass this array to my JavaScript, I've been attempting the following ...

Input ENTER triggered JSON path loading

Upon clicking "enter", I am looking to display the description corresponding to the title. To achieve this, I have defined a variable to store the path of the description: var descri = json.query.results.channel.item.map(function (item) { return item. ...

Adding turbolinks to an HTML document can be achieved without the need for a

Recently delving into the world of turbolinks, I discovered that it can be employed independently without relying on a client-side javascript framework. Eager to test this out, I created a bootstrap 4 template and attempted to install it. Firstly, I downl ...

Storing the last encountered bracket type in JavaScript using regular expressions

My JavaScript code needs to match text that meets the following criteria: (surrounded by parentheses) [surrounded by square brackets] not surrounded by either type of bracket Given the expression... none[square](round)(accept]able)[wrong).text ... the ...

defiant underscore refusing to function

I'm currently working on a text editor, but I'm facing an issue with the remove underline functionality that doesn't seem to be working as expected. For reference, you can check out a working code example here: jsfiddle Below is the part of ...

Establishing a connection to MongoDB using JavaScript

Currently, I'm working on a fun little project revolving around a web calendar. For this project, I've decided to integrate mongoDB into it. Fortunately, I have successfully configured MongoDB and established a connection with PHP. However, I am ...

In what way are these fonts being displayed through the utilization of a .js file?

Why are people opting for unique fonts on their browsers using .js files instead of graphics? For example, like typekit? ...

Retrieving Data in mysql using Arrays

Is it possible to group inventory results by model and manufacturer name, displaying the number of matching items and one result per group? I am also looking to retrieve all inventory IDs within each group. Any thoughts on how to achieve this? For your in ...

Contrasting angular.fromJson and $scope.$eval in their utilization of a JSON string

When working with my angularjs applications, I typically parse JSON strings using the angular.fromJson method: var myObject=angular.fromJSON(jsonString); However, it seems that achieving the same result is possible by utilizing $scope.$eval: var myObjec ...

Leveraging Python to authenticate on a website using JavaScript and secure HTTPS connection

I am looking to utilize python for logging into a website that utilizes javascript and https encryption. The specific site I'm referring to is: My goal is to create a python script that successfully logs in, with the intention of later translating th ...

Tips for transferring information from a child component to its parent using a click event in the parent component

My React application is designed to generate quizzes. The main component, <CreateQuiz/>, contains a child component called <QuestionForm/>. Additionally, within the <CreateQuiz/> component, there is a button labeled "Add Question" which a ...

Guide for adding Chinese characters with digital signature in your jsrsasign.js code

I am currently working on integrating with third-party organizations that require a digital signature to be added to the data in the request header. After some research, I decided to utilize the jsrsasign.js library for handling the digital signature proc ...

Refine the table by selecting rows that contain a specific value in the href attribute of the <a> tag, and display the parent row when the child row

I've been working on filtering and searching the table below based on the href value. My code successfully filters the displayed columns in the table, but it fails to work when I search for a string within the href attribute. For instance, if I searc ...

Loading textures locally using three.js is functioning properly, however, remote loading is not functioning as

I have customized an official example for the Loader object to showcase a specific issue. My goal is to generate a mesh with a texture map that loads before creating the geometry. Currently, I am facing a problem where local files load properly, but remote ...

React callbacks involve the interaction between three different components

Currently, I am working with 3 distinct components: -The friendsPage component contains a list of friends and invitations to friends -The friendComponent displays detailed information about a friend along with possible actions (which are handled in the t ...

Is there a way to input two different values into my search bar?

I've been attempting to enhance my searchbar by adding the value of "organization.name" to filter the list along with "organization.topic". However, it doesn't seem to be working as intended. const filteredOrganizations = context.allOrganizations ...

Rotating a specific part of a model in THREE.js

Whether it's feasible to adjust the position or rotation of a component within an OBJ (or similar format) model. Can one manipulate a single model instead of needing multiple ones? What is the optimal approach to achieve this goal effectively? Appreci ...

Tips for generating a single CSS file that adapts to various screen sizes without the ability to modify the class names within the library

I am currently learning ReactJs and JavaScript and I have a question on how to optimize this css setup effectively. I am utilizing the react-responsive library to detect screen sizes and determine the best layout for my project. The issue I am facing is ...