Total of the various components within an array

I'm new to programming and I'm trying to calculate the sum of all elements in an array. I've written this code, but it doesn't seem to be working properly. Can someone help me find my mistakes?

function ArrayAdder(_array) {
    this.sum = 0;
    this.array = _array || [];
}

ArrayAdder.prototype.computeTotal = function () {
    this.sum = 0;
    this.array.forEach(function (value) {
        this.sum += value;
    });
    return this.sum;
};

var numbersArray = new ArrayAdder([1, 2, 3]);
console.log(numbersArray.computeTotal());

Answer №1

this in the context of a forEach callback actually refers to the global window object. To define the context of the callback, utilize the second argument of Array#forEach function.

this.array.forEach(function (value) {
    this.sum += value;
}, this); // <-- Now `this` is bound to the callback function.

function ArrayAdder(_array) {
    this.sum = 0;
    this.array = _array || [];
}

ArrayAdder.prototype.computeTotal = function () {
    this.sum = 0;
    this.array.forEach(function (value) {
        this.sum += value;
    }, this);
    return this.sum;
};

var myArray = new ArrayAdder([1, 2, 3]);

console.log(myArray.computeTotal());
document.write(myArray.computeTotal()); // For demonstration purposes


If you're seeking an alternative approach, consider using Array#reduce, demonstrated here with Arrow functions

var sum = arr.reduce((x, y) => x + y);

// Please note: This may not work in all browsers,
// verify compatibility in latest versions of Chrome/Firefox

var arr = [1, 2, 3];
var sum = arr.reduce((x, y) => x + y);

document.write(sum);

Answer №2

When dealing with the `forEach` function, the reference of `this` is altered. It is recommended to update your code as shown below:

function ArrayAdder(_array) {
  this.sum = 0;
  this.array = _array || [];
}

ArrayAdder.prototype.computeTotal = function() {
  this.sum = 0;
  var that = this;
  this.array.forEach(function(value) {
    that.sum += value;
  });
  return this.sum;
};

var myArray = new ArrayAdder([1, 2, 3]);
console.log(myArray.computeTotal());

The code above preserves the reference of `this` by using `that` for computation purposes.

Answer №3

One way to efficiently accomplish this task is by utilizing the reduce method for arrays. Here's a simple example:

this.numbers = [5, 10, 15, 20];
this.total = this.numbers.reduce(function(num1, num2) {
  return num1 + num2;
});

Answer №4

Give this a shot:

  const numbers = [10, 20, 30, 40, 50];
  const total = numbers.reduce((a, b)=> a+b);
  console.log(total);

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

Building a static support button within Laravel

I am looking to add a fixed button to my homepage that, when clicked, will open a support page above the button. I have seen examples of this on various websites, but I am struggling to implement them due to complex embedded codes and JavaScript. Can you ...

The issue with CSS filter invert not functioning properly in Mozilla Firefox is causing complications

I am currently developing a small Firefox add-on designed to make reading pages at night more comfortable. The goal is to invert page colors without affecting images. Here is the code snippet I am using: document.body.style.filter = "invert(100%)"; var i ...

Break down a data structure into a type that includes multiple options

Is it possible for Typescript to support type or interface "destructuring" (if that's the right term)? I am attempting to achieve something similar to the code snippet below: type SomeRandomType = { propertyOne: string; propertyTwo: number; ...

Retrieving JSON information from the server

I have been working with the knockout.js framework and adapted a basic contacts form example to suit my needs. I am able to successfully store values in my database, but I am encountering difficulties when trying to load values from the server. Despite h ...

Differences Between Pointers for int and char Arrays in C

I see that there have been similar inquiries before, however, this one pertains specifically to arrays. Here is an example of what I can do: char *names[] = { "John", "Paul", "George", "Ringo" }; and then: printf("%s\n", names[0]); But why doesn& ...

What is the best method for submitting an array of objects using Axios, Formik, and React.js?

Hello, I am facing an issue with posting an array of objects using axios and Formik while also utilizing npm react-select. Here is my initial data: const [initialValues, setInitialValues] = useState( { nom: "",drugs: [{}] ...

Sequelize.js - Establishing Relationships Between Two Tables

Technologies used: Node.js, Express.js, Sequilize.js I am facing a challenge in connecting two tables within my project. The tables in question are the user table and the color table. Each color is associated with a user, where a single user can have onl ...

The latest version of Next.js, 11.1.0, does not support monitoring for code changes within the node

In the latest version of Nextjs (11.1.0), there seems to be an issue where code changes in the `node_modules` directory are not being watched, unlike in the previous version (10.2.1). While working on a project with Nextjs 11.1.0, I have tried explicitly ...

Differentiating between clicks and dragging interactions within an HTML 5 canvas

I am working on creating a basic map using the HTML 5 canvas. The idea is that dragging the mouse will move the map, and clicking will select the nearest waypoint. However, I have encountered an issue where I receive the click event even when dragging the ...

What is the best way to display a PDF in a web browser using a JavaScript byte array?

I have a controller that sends the response Entity as a byte array in PDF form to an ajax call. However, I am struggling to display it in the browser despite trying various suggestions from old Stack Overflow questions. Here is the response from the Sprin ...

Building a Vue application with customized authentication for the Google Calendar API in JavaScript

Struggling with understanding the migration from GAPI to GIS in Vue? Google has provided a helpful document on this topic: https://developers.google.com/identity/oauth2/web/guides/migration-to-gis#server-side-web-apps Attempting to implement code from the ...

Arranging Arrays with Multiple Dimensions in PHP

I have a unique data structure that resembles the following: Array ( [13] => Array ( [name] => Blah blah [description] => Blah blah blah [parent_group_id] => 8 [display] => Blah : Blah ...

Using Django to send AJAX POST requests to pass JavaScript variables for form initialization

Currently, I am engaged in a Django project where I have managed to gather all my variables in JavaScript and now attempting to initialize a form (within a modal popup) on the same page without any need for refresh. The form is successfully displaying insi ...

Angular DataTable jQuery

I am a huge fan of jQuery DataTable, but I have come to realize that when using AngularJS, it does not function properly. Instead of displaying the data with pagination, it shows "No data available in table Showing 0 to 0 of 0 entries." I have checked ou ...

Having trouble with sluggish performance on openbim-components? The OrthoPerspectiveCamera tends to slow down or get stuck when zooming

While using the OrthoPerspectiveCamera in my App (from openbim-components package), I am facing an issue. Whenever I zoom into my model, it automatically switches to FirstPerson mode. This change makes it extremely slow to navigate and zoom in/out of the s ...

Guide to incorporating a defined quantity of elements into JavaScript arrays based on a certain condition

I am currently working on a task involving the selection of columns from a table, with a restriction of 20 elements. The objective is to select all items up to the specified limit. Current Status: 18/20 Next column contains 10 elements Clicked on "select ...

Error Encountered: The element specified is not recognized as a <Route> component. All children components within <Routes> should be either a <Route> or <React.Fragment>

I've been trying to integrate the strip API key, but I'm having trouble finding a solution in the new react-router-dom version Here is the detailed error message: The above error occurred in the component: at Routes (http://localhost:3000/stati ...

Is memory allocated to the array's name?

When we create an array in C inside a function like this - int a[] = {1,2,3,4}; A contiguous block of memory is allocated in the stack segment at a particular address, let's say 1000. 1000 | v +--+--+--+--+ |1 |2 |3 |4 | +--+--+--+--+ If we have a ...

Comparing $.fn.fancybox and $.fancybox: What sets them apart?

I'd like to understand the distinction between the two items shown above. In what ways do they differ from each other? ...

How can I retrieve the initial character from each string within an array using JavaScript?

As someone who is new to coding, I have a question that may seem simple to others. If I have an array like this: ["John", "Will", "Mike"], how can I display only the first letter of each element? var friends = ["John", "Will", "Mike"]; I initially though ...