Pass variable from array into a function - javascript

I have this function:
function getTotal () {
var args = Array.prototype.slice.call(arguments);
var total = 0;
for (var i = 0; i < args.length; i++) {
total += args[i];
}
return total;
}
Lets say that I have an array that is filled with numbers and I do not know the length of it:
var numArray = [ ..., ... ];
How can I call the function getTotal by passing in every element in the numArray as a parameter?

In ES6 you can do this:
getTotal(...numArray);
It called Spread syntax. For more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator

You can call the function using Function.prototype.apply. It will pass the Array as arguments to your function.
function getTotal () {
var args = Array.prototype.slice.call(arguments);
var total = 0;
for (var i = 0; i < args.length; i++) {
total += args[i];
}
return total;
}
var numArray = [1,2,3,4];
console.log( getTotal.apply( null, numArray ) );
Keep in mind you have a typo in your for loop. Should be args.length, instead of arg.length.

Please try this. Hope it helps
var sum = [1, 2, 3, 4, 5].reduce(add, 0);
function add(a, b) {
return a + b;
}

If you use the spread operator, you may also want to ES6ify your code:
function getTotal(...vals){
return vals.reduce((a,b)=>a+b,0);
}
getTotal(...[1,2,4]);

Why not just do this:
function getTotal (args) {
var total = 0;
for (var i = 0; i < args.length; i++) {
total += args[i];
}
return total;
}
var numArray = [1,2,3];
console.log(getTotal(numArray)); //6

Related

How to pass arguments from a javascript function to another function without calling it?

I am trying to pass variable after a calculation from a function to another function by passing it as an argument. But when I do this, the function gets called right away.
let myarr = [2,4,6,8];
function checkaverage() {
let sum = 0;
for (let i=0; i<myarr.length; ++i) {
sum = sum + myarr[i];
}
let averageis = sum/(myarr.length)
averagealerter(averageis);
}
checkaverage();
function averagealerter(averageis) {
alert("the average is "+ averageis)
};
Here, I passed the "averageis" variable as argument to function "averagealerter" for later use. But it gets called right away. What I want to accomplish is later call it by using "averagealerter()".
let myarr = [2,4,6,8];
function checkaverage() {
let sum = 0;
for (let i=0; i<myarr.length; ++i) {
sum = sum + myarr[i];
}
let averageis = sum/(myarr.length)
return averageis;
}
function averagealerter() {
alert("the average is "+ checkaverage())
}
// call the averagealerter() function when required.
You could .bind the averageis variable to the averagealerter and return that copy of the function.
Then, call that function to achieve the result:
let myarr = [2,4,6,8];
function checkaverage() {
let sum = 0;
for (let i=0; i<myarr.length; ++i) {
sum = sum + myarr[i];
}
let averageis = sum/(myarr.length)
return averagealerter.bind(undefined,averageis);
}
function averagealerter(averageis) {
alert("the average is "+ averageis)
};
let myaveragealerter = checkaverage();
myaveragealerter();
All you need to do is make the checkAverage function return a value so that the value can be used in other functions by just calling the function like below
let myarr = [2,4,6,8];
function checkaverage() {
let sum = 0;
for (let i=0; i<myarr.length; ++i) {
sum = sum + myarr[i];
}
let averageis = sum/(myarr.length)
return averageis;
}
function averagealerter() {
alert("the average is "+ checkaverage())
};
averagealerter()

confusion regarding array.average() functionality in "var avg = array.average()"

Cheers guys. I was asked to make this code work in a learning challenge and I'm not sure how to tackle the "array.average()" part, as it's not a function.
What I was asked was this:
var array = [5,44,23,11,55,68];
var avg = array.average();
console.log(avg);
So far, I've tackled the averaging of the array like this:
function average(){
var total = 0;
for (var i = 0; i < array.length; i++) {
total += array[i];
}
var avg = total / array.length;
}
Any and all corrections are welcome. This is 100% learning based so everything helps.
First attach the function to your array object, and then make sure to return a value at the end of it:
var array = [5,44,23,11,55,68];
array.average = () => {
var total = 0;
for (var i = 0; i < array.length; i++) {
total += array[i];
}
var avg = total / array.length;
return avg;
}
var avg = array.average();
console.log(avg);
(avoid mutating native prototypes)
Suppose you need to add it in the Array.prototype (which is a bad idea), use Object.defineProperty to add it in as non-enumerable and won't clash with other native methods:
var array = [5,44,23,11,55,68];
Object.defineProperty(Array.prototype, 'average', {
enumerable: false,
value: () => array.reduce((a,b) => a + b) / array.length
});
console.log(array.average())
Add average function to Array.prototype:
var arr = [5,44,23,11,55,68];
Array.prototype.average = function() {
return this.reduce(function(acc, cur) { return (acc + cur); }, 0) / this.length;
}
var avg = arr.average();
console.log(avg);

JavaScript curry / schönfinkeln

Lets say I have the following functions declared
function curry(fn) {
var args = [];
// push everything but function itself into args
for (var i = 1; i < arguments.length; ++i) {
args.push(arguments[i]);
}
return function() {
var args2 = [];
for (var i = 0; i < arguments.length; i++) {
args2.push(arguments[i]);
}
var argstotal = args.concat(args2);
return fn.apply(argstotal);
};
}
function add(a,b){return a + b};
What im trying to do is obvious, I want to curry the add function which works great itself
var addCurry = curry(add);
addCurry(10, 20, 12314) // should deliver 30, gives NaN
Somehow it returns NaN and I dont know what Im doing wrong... Anybody got an idea?
You have an off-by-one error here: return fn.apply(argstotal)
The first argument to Function.prototype.apply is a scope, the value of this within the invocation, not the first argument. If you were to print out the arguments from within your curried function, you would see:
function curry(fn) {
var args = [];
// push everything but function itself into args
for (var i = 1; i < arguments.length; ++i) {
args.push(arguments[i]);
}
return function() {
var args2 = [];
for (var i = 0; i < arguments.length; i++) {
args2.push(arguments[i]);
}
var argstotal = args.concat(args2);
return fn.apply(argstotal);
};
}
function add(a, b) {
console.log('debug', this, arguments);
return a + b;
}
var cadd = curry(add, 1);
cadd(2);
You can very easily fix this in two ways:
Pass this through to the curried function
Ignore this and do not set it for curried functions
The first option is probably better, as it will surprise developers less. You can implement that using:
function curry(fn) {
var args = [];
// push everything but function itself into args
for (var i = 1; i < arguments.length; ++i) {
args.push(arguments[i]);
}
return function() {
var args2 = [];
for (var i = 0; i < arguments.length; i++) {
args2.push(arguments[i]);
}
var argstotal = args.concat(args2);
return fn.apply(this, argstotal); // <-- only change
};
}
function add(a, b) {
console.log('debug', /* this, */ arguments);
return a + b;
}
var cadd = curry(add, 1);
cadd(2);
The second option can be implemented with fn.apply(null, argstotal).

Making a function that adds numbers in an array and returns their sum in javascript

I'm trying to create a function that will add the numbers in an array and return their sum. For some reason it's returning 1 instead of 15 and I'm not sure why.
var myArray = [1,2,3,4,5];
function addThemUp(myArray) {
var arrayTotal = myArray.length;
var totalSum = 0;
for(var x = 0; x <arrayTotal; x++) {
totalSum += myArray[x];
return(totalSum)
}
}
addThemUp(myArray)
You placed the return statement inside the loop, so it will sum the first element only and then return. Instead, you should allow the loop to complete, and return the sum only after its done:
function addThemUp (myArray) {
var arrayTotal = myArray.length;
var totalSum = 0;
for(var x = 0; x < arrayTotal; x++){
totalSum += myArray[x];
}
return(totalSum); // This is where the return should be
}
In your case, you need to fix where the return of totalSum is, to be the last statement of your function (after the loop).
That being said, you may find that adding up all the numbers in an array is much cleaner and simpler to do with reduce:
function addThemUp(myArray) {
return myArray.reduce(function(a, b) { return a + b; });
}
var myArray = [1, 2, 3, 4, 5];
console.log(addThemUp(myArray));
You should return sum after for loop
var myArray = [1, 2, 3, 4, 5];
function addThemUp(myArray) {
var arrayTotal = myArray.length;
var totalSum = 0;
for (var x = 0; x < arrayTotal; x++) {
totalSum += myArray[x];
}
return totalSum;
}
console.log("Sum of all elements: " + addThemUp(myArray));

pass a number into an array using a for loop

I have to do a function to return an array with all positive numbers from 0 to n (inclusive, meaning n should be included in the array and n will be a number passed to the function as parameter.
This is what i have:
function arrayWithNumbersUpTo(n) {
for(var i = 0; i <= n; i++) {
arr.push(i);
return arr;
}
}
var arr = [];
I've been struggling for over two hours to do what I am sure is a simple solution, please help!
You have to call the return outside the for loop:
function arrayWithNumbersUpTo(n){
var arr = [];
for(var i = 0; i <= n; i++){
arr.push(i);
}
return arr;
}

Categories