Calculate the sum of an array and then invoke a callback function from within another function

I'm currently facing a challenge where I need to calculate the total sum of an array using the .reduce() method within a function. Instead of simply returning the sum, I am required to call a callback function and pass the sum as an argument.

Though I believe I am using the .reduce() method correctly, I keep receiving 'undefined' as a result. I'm struggling to understand how I can effectively invoke a function within another function.

Any assistance or explanations on this matter would be greatly welcomed!

Question: Can you sum all integers in the numbers array and then call a callback function with the sum as an argument?

Here is my code:

function sumArray(numbers, cb) {
  // Insert code here

  const result = numbers.reduce(function(sum, currentValue) {
    return sum + currentValue;
  }, 0);

  cb([1, 2, 3, 4, 5], result);
}

function addTwo(num) {
  const result = num + 2;
}

Answer №1

The query indicates

Instead of returning the total, call cb and input the total to it.

This simply translates to cb(sum), nothing complicated beyond that. This callback allows for additional functionality to be implemented.

For instance:

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

function sumArray(numbers, cb) {
  var sum = numbers.reduce(function(sum, currentValue) {
    return sum + currentValue;
  }, 0);
  cb(sum);
}

function outputSum(sum) {
  console.log("The total is " + sum);
}

function addTwo(sum) {
  console.log(sum + 2);
}

sumArray(numbers, outputSum);
sumArray(numbers, addTwo);

Answer №2

Your assignment requires some careful consideration, so I'll give you a nudge in the right direction without revealing too much.

Instead of simply calculating the sum with

numbers.reduce(function(sum, currentValue) {
, make sure to store it in a variable like var reduced = things.reduce(...).

It seems like cb is designed to accept only one argument (the sum), but you are currently passing an array and another variable result (which hasn't been declared yet). Make sure to adjust your approach accordingly.

Answer №3

Below are the issues discovered:
1. It is necessary for your reduce() function to return its output to the result variable. Without either returning the output or defining the result variable, this functionality will not work correctly.
2. In case addTwo() is the callback function, it should operate with a single variable. Since there's no indication of where the cd callback is meant to go in the code snippet provided, it seems that it may have been omitted. Please ensure you include it as follows:

function sumArray(numbers, cb) {

 var result = numbers.reduce(function(sum, currentValue) {
    return sum + currentValue;
 }, 0);

 cb([1, 2, 3, 4, 5], result);

}

function addTwo(num) {
 const result = num + 2;
}

Answer №4

Looks like you're attempting to achieve something along these lines.

  1. Make sure to save the reduced return value.
  2. You should also return the callback function.

In order to access the internal callback, you need to return it.

function sumArray(numbers, cb) {
  // add your code here
  let result = numbers.reduce(function(sum, currentValue) {
    return sum + currentValue;
  }, 0);

  return cb([1, 2, 3, 4, 5], result);

}

function sumTwo(arr, num) {
return  Number(num + 2);
}

console.log(sumArray([1, 2, 3, 4, 5], sumTwo));

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

How can I dynamically update an img src using JavaScript on a PHP webpage?

I have a PHP page where I display image thumbnails. I am trying to implement a feature where the thumbnail expands in another image on mouseover. Here is the PHP code snippet: echo "<tr><td><a href='$imgrow[location]' target=&ap ...

Which Angular component, directive, or pipe would be best suited for creating dynamic HTML content similar to this?

(I am transitioning from React to Angular, so please bear with me if my question has a hint of React influence.) I am in need of developing an Angular component that can accept a string along with a list of terms within that string for displaying tooltips ...

Is it possible to redefine a function that is attached to $ctrl outside of the AngularJS framework?

Within my DOM, there exists an element containing ng-click="$ctrl.goToHome(), which is connected to the logo on my site. This particular element is generated by a third-party AngularJS application. The complete element can be seen below: <img ng-if=":: ...

What could be the reason for my jQuery script not functioning properly on my web form that was inherited from a MasterPage?

In the head of my master page, I have included: <script src="Script/jquery.min.js"></script> <link href="Stylesheet/Master.css" rel="stylesheet" /> My webform (Login.aspx) inherits from this master page, and in Login.aspx I have: <a ...

Transmit information using jQuery to an MVC controller

I am developing an ASP.NET MVC3 application and need to send three pieces of data to a specific action when the user clicks on an anchor tag: <a onclick='sendData(<#= Data1,Data2,Data3 #>)'></a> Here is the javascript function ...

The scope attribute is not functioning as expected in the loopback model

After utilizing an "include" : "organization" query within the context of my request.json file, a related model, I noticed that the resulting output from the query does not include the intended relation. The structure of the model (request.json file) is ...

How can PHP effectively interpret JSON strings when sent to it?

When working with JavaScript, I am using JSON.stringify which generates the following string: {"grid":[{"section":[{"id":"wid-id-1-1"},{"id":"wid-id-1-4"}]},{"section":[{"id":"wid-id-1-5"}]},{"section":[{"id":"wid-id-1-2"},{"id":"wid-id-1-3"}]}]} I am ma ...

Converting a curl command to a $.ajax() call in JavaScript: A step-by-step guide

I'm attempting to retrieve data from the Zomato API by using jquery ajax, however, they have provided a curl command instead. curl -X GET --header "Accept: application/json" --header "user-key: key" "https://developers.zomato.com/api/v2.1/cities" Is ...

The distinction between using document.getElementById and document.getElementsByClassName in JavaScript

One thing that stands out is why does document.getElementsById function as expected here <div id="move">add padding</div> <button type="button" onclick="movefun()">pad</button> <script> function movefun() { document.get ...

What is the proper way to integrate three.js (a third-party library) into the view controller of an SAPUI5 application

Seeking a Solution Is there a way to integrate the three.js library into SAPUI5 in order to access it using THREE as the root variable in my main view controller? I attempted to create a directory named libs within my project folder and include it in the ...

Issue with Accordion Panel Content Scroll Bar

Hello there, I've encountered a puzzling problem with my website. My objective is to insert a Time.ly Calendar widget into one panel of my accordion. On this page, "TOURNAMENTS: , the widget appears exactly as desired. However, when I replicate the c ...

Retrieve the date from the event

Incorporating fullcalendar v2.0.2, I am currently developing a copy/paste system for events. By right-clicking, I am able to copy the event with the help of a small menu. Upon right-clicking on the calendar during a week view, I am tasked with calculating ...

ng-include not functioning properly within ng-table

In the table, there is a data structure <tr ng-repeat="question in $data" ng-include="'/views/partials/questionList.html'"></tr> Within the questionList.html file: <td class="top-td" data-title="'ID'" sortable="&ap ...

Decoding a changeable JSON structure

As I am working on parsing a JSON and looking for a specific key within the JSON object, I am facing an issue due to the changing structure of the JSON. It is not feasible to hard code the path for searching. Are there any alternative methods to parse this ...

Obtain the parameter fetching identical identifier

When I click on a search result on the left, I want it to load in the right div without refreshing the page or opening a new one. The search generates three results with pagination. However, no matter which result I click, the same ID loads. Can anyone spo ...

Obtaining Serialized Data

Using the JavaScript serializer to send data to JavaScript: var jsSerializer = new JavaScriptSerializer(); var result = (from c in dt.AsEnumerable() select new { Latitude = c.F ...

A subtle X icon tucked away in the corner of the homepage, a result of the jquery modal window

Struggling with an issue on a client's website - there are multiple jquery sections with buttons that open modal windows. The problem is that the close button for these modals appears on page load and is situated at the top right of the homepage. Is t ...

Attempting to design a form that will trigger a print dialog box displaying all the information entered in the form

I am currently working on developing a form that will allow users to input information such as Name, Age, Gender, Hobbies, Contact details, and Photo in order to create a resume. My goal is to build a simple local HTML-based application that generates a RE ...

C# Selenium Struggles to Find a Concealed Element coded in Javascript

Can anyone help me locate the element with the tag <span _ngcontent-c19=""> ACME Nursing </span> using Xpath or any other method? I have attempted various ways to use actions in order to moveToElement, as well as other methods, but I am unable ...

Challenges Encountered with jQuery/AJAX Form Processing

I am currently facing an issue with two files in my project. The main file, index.php, contains JavaScript code within the head section. Here is the snippet of JavaScript: <script src="http://code.jquery.com/jquery-latest.min.js" type= ...