Using JavaScript: How to utilize Array.reduce within a function that also accepts arguments

let foo = 0;
let bar = 0;
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [6, 7, 8, 9, 10];

function calculateSum(arr) {
    return arr.reduce((accum, val) => accum + val, 0);
}

foo = calculateSum(arr1); // Expect foo to equal 15
bar = calculateSum(arr2); // Expect bar to equal 40

I want to reuse this function for different arrays and values. Instead of passing the sum as an argument, let's update the value directly by returning it from the function.

The new syntax maintains clarity in the code while achieving the desired functionality.

Answer №1

If I have it clear, all you really need is a simple sum function:

var x = 0;
var y = 0;
var nums1 = [1, 2, 3, 4, 5];
var nums2 = [6, 7, 8, 9, 10];

const calculateSum = (numbers) => numbers.reduce((result,current) => result + current)

x = calculateSum(nums1)
y = calculateSum(nums2)
 
console.log(x)
console.log(y)

Answer №2

Primitive types in JavaScript are passed by value, while objects are passed by reference. Although it is possible to achieve this by wrapping the variable foo in an object, it is not recommended to design code in this way. Modifying function arguments can make the code difficult to understand and debug.

var foo = { value: 0 };
var bar = { value: 0 };
var arr1 = [1, 2, 3, 4, 5];
var arr2 = [6, 7, 8, 9, 10];
    
function getSum(arr, sum) {
    sum.value = arr.reduce(function(accum, val) {
      return accum += val;
    }, 0)
}
    
getSum(arr1, foo);
getSum(arr2, bar);

console.log(foo.value);
console.log(bar.value);

If possible, it is advisable to find a solution to your problem without mutating variables.

Many linting tools, such as eslint, will raise an error if they detect mutation of function arguments.

Instead, it is better to separate the sum function from the assignment of the resulting value:

var arr1 = [1, 2, 3, 4, 5];
var arr2 = [6, 7, 8, 9, 10];
        
function sum(arr) {
    return arr.reduce(function(acc, next) { return acc + next });
}

var foo = sum(arr1);
var bar = sum(arr2);
    
console.log(foo);
console.log(bar);

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

I am facing issues with running my project due to a gyp error. Can anyone provide guidance on resolving this problem?

Every time I execute my code, I encounter the same persistent error. Despite attempting to resolve it by uninstalling and reinstalling Node and npm, the issue persists. Furthermore, the lack of "node_modules" exacerbates the problem. How can I rectify this ...

What is the best way to increase the value of a variable using jQuery?

As I work on adding dates to a slider, I find myself needing to increment the values with each click. Initially, I start with the year - 2. $('#adddates').click(function() { var year = 2; $("#slider").dateRangeSlider({ bounds: { ...

Exploring the World of AJAX with CodeIgniter

I've been on the hunt for a solid working example of using AJAX with Codeigniter, but most resources I've found are outdated. As an AJAX beginner, I'm struggling to find up-to-date tutorials. What I'm aiming for is an input form on a w ...

Steps for storing div content (image) on server

Currently in the process of developing a web application that allows users to crop images. The goal is for users to have the ability to email the URL so others can view the cropped image, ensuring that the URL remains active indefinitely by storing every c ...

Ajax: The response from xmlhttp.responseText is displaying the entire inner HTML rather than the specified text needed

This is my Ajax function. It is functioning correctly, however after the function is called, it returns a response containing HTML tags and required text. Response in value variable " <br/> <font size='1'> <table class='x ...

Issue with Vue3: The imported module is not defined

Update: I recently downgraded vue-cli to version 4.5.19 and now the code is functioning properly. It seems like there might be an issue related to vue-cli or its dependencies. I encountered a problem while working on a simple vue.js project using vue-cli. ...

What is the best way to position a container div over another container using Bootstrap or CSS?

https://i.sstatic.net/q1qGi.png I'm working on a Bootstrap 4 layout where container B needs to overlay part of container A. I want to achieve a design where container B appears on top of container A. Any suggestions or references on how to achieve th ...

Tips for pressing the enter key to submit when faced with two buttons

I am developing a form with two input fields and their respective submit buttons. I want users to be able to enter text into either field, hit the Enter key, and have it trigger the same action as clicking the submit button. Currently, pressing Enter after ...

Display HTML content within a Material-UI Card component using React

Currently, I am utilizing the < CardHeader /> component nested within a < Card />. <CardHeader title={card.title} subheader={`${moment(card.createdAt).startOf('minute').fromNow()}` + ' by ' + <div>ABC</div>}/ ...

Arrays contain multiple elements, not just a single item

Is it possible to display multiple objects in one container? For instance, I have an array let array = [1, 2, 3, 4, 5, 6, 7, 8, 9]; array.forEach((item, index) => ( <div> <div> item 1, 2, 3 </div> <div> item 4, 5, 6 </div ...

The dimensions of the sprites within Three.js geometry

I am interested in creating an animation of sprites moving along a figure, particularly sprites that walk along the figure. An example of what I envision can be seen here: http://armsglobe.chromeexperiments.com/ I found some helpful information related t ...

Can we rely on JavaScript to maintain the order of object properties?

Let's say I define an object in the following way: var obj = {}; obj.prop1 = "Foo"; obj.prop2 = "Bar"; Is it guaranteed that the object will always appear exactly like this? { prop1 : "Foo", prop2 : "Bar" } In other words, will the properties reta ...

How to manipulate iframe elements using jQuery or JavaScript

Hey there, I have a simple task at hand: I have a webpage running in an iFrame (located in the same folder on my local machine - no need to run it from a server) I am looking to use JavaScript to access elements within this iFrame from the main page. How ...

Samsung Galaxy S7 can interpret alphabetical parameters as numbers in a link sent via SMS

When trying to open a text message with a new message on my website using a link, I encountered an issue specifically with the Galaxy S7. The following code works on most Android phones: sms:5555555555?body=JOIN However, on the Galaxy S7, the "?body=JOIN ...

Improving Three.js performance for a single, substantial model

I am currently developing a hybrid file browser and 3D model viewer. My goal is to seamlessly load models of various formats, specifically .OBJ files, into the scene while maintaining a smooth framerate with the help of orbitControls.js. Most of the optim ...

Acquiring the content of elements contained within a div container

On a webpage, I have included multiple div elements with unique IDs and the following structure: <div class="alert alert-info" id="1"> <p><b><span class="adName">Name</span></b><br> ...

Using jQuery, target the specific elements that have certain data attributes assigned to them

Is there a way to target elements with a specific data attribute and a unique class using jQuery? For instance, I want to select these elements: <div data-roomid="55" data-status="NoData"></div> <div data-roomid="55" data-status="Open"> ...

Executing jQuery after the body has finished loading

I'm trying to execute a JavaScript function once the body has finished loading. My framework loads the header and footer from static files, while the body content is dynamic. I read online that I should place the $(elem).load(function()) at the end of ...

Having trouble with implementing Nested routes in Vuejs?

main.js import Vue from "vue"; import App from "./App.vue"; import VueRouter from "vue-router"; import HelloWorld from "./components/HelloWorld"; import User from " ...

Why does the lazy loading feature keep moving the background image around?

While trying to incorporate lazy loading on my website, I encountered an issue where the image position would change after it was fully loaded and made visible. I experimented with rearranging the order in which my JavaScript and CSS files were called, bu ...