Javascript: Inserting data from an array into function parameter - javascript

I have only been learning javascript for 2 weeks, so apologies if my question seems weird/doesn't make sense. I'm learning the basics of arrays, and to help me learn I like to practise and play around with the code but I can't seem to figure this one out.
I've created a simple function, and wanting to call upon the function to calculate the sum of variables in an array. Here is my code below:
//functions
function simpleCalc (a,b) {
var result = a + b;
return result;
}
//array
var myArray = [12,567];
//final calculation
var total = simpleCalc([0],[1]);
alert("The total is " + total);
Can anyone please shed any light as to how I input the numbers "12" and "567" into the function parameters? The result here as it stands outputs to "01"
Thanks

You have two options:
Your option but, it is very limited to only two values.
You need to pass reference to your array elements like so (myArray[0], myArray[1])
Create new function - let's call it sumValuesInArray(), pass an array and calculate all values inside an array using for loop.
See working example here:
//functions
function simpleCalc (a,b) {
var result = a + b;
return result;
}
//array
var myArray = [12,567];
//final calculation
var total = simpleCalc(myArray[0],myArray[1]);
//alert("The total is " + total);
// OR
function sumValuesInArray(array) {
var total = 0;
for(i = 0; i < array.length; i++) {
var element = array[i];
total += element;
}
return total;
}
console.log(sumValuesInArray(myArray));

You don't specify the array but only indexes :
var total = simpleCalc([0],[1]);
So, it passes two array objects : [0] and [1].
The concatenation of them here :
var result = a + b;
has as result the 01 String.
To pass the two first elements of myArray, try it :
var total = simpleCalc(myArray[0],myArray[1]);

You need to access the array values by index. You do this using the brackets WITH the name of the array. If you pass the brackets with numbers inside, you're creating new arrays.
It should be:
var total = simpleCalc(myArray[0],myArray[1]);

Related

How to make an array with key-value pairs as integers, and loop through each key value pair to pass as arguments to my function?

What I want to do is:
I have a function that animates a div's margin-left in percentage, with an associated distance counter (for another function):
function animateValue(amount, counter) {
myDivToAnimate.animate({
marginLeft: amount + '%'
}, 1200, function () {
slideCounterValue = counter;
});
}
And I'm calling it as follows, decimal places are required for this:
animateValue(-100.5, -1)
What I want to do is make an array or an object (I'm not sure which), that has the arguments from above. So for example:
var myArray = [{-100.5: -1},{-200.8: -2},{-312.5: -3}...]
and then pass these to my animateValue() function.
I'm not sure how to either:
Create the array with integers, which are negative and have decimals
Pass these pairs from the array to my animateValue() arguments.
Finally, once I have sorted them, I need to randomize the array key-value pairs that are pulled, so that each time it animates to a different margin-left and associated counter value.
Probably it's a simple answer but I can't seem to get my head around it.
You can not have JSON key as negative integer. Please take it as a string and convert it according to you need.
var myArray = [{"-100.5": -1},{"-200.8": -2},{"-312.5": -3}];
for(let i in myArray) {
let tempObj = myArray[i];
for(let key in tempObj) {
//console.log(parseFloat(key) + "\t" + tempObj[key]);
//call your function here
animateValue(key, tempObj[key]);
}
}
function animateValue(a, b) {
console.log(a + "\t" + b);
}
If you choose to keep values inside arrays, like below,
var myArray = [[-100.5, -1],[-200.8, -2],[-312.5, -3]];
then it is easy iterate over them and pass to a function.
Let's define a function, than accepts two numbers and uses them (in our case returns the value sums).
foo = function(a,b) { return a+b; }
then iterate over myArray and pass the inner array values as parameters to foo function.
> for(i=0; i<myArray.length; i++) {
... console.log(foo(myArray[i][0], myArray[i][1])); }
-101.5
-202.8
-315.5
or let's mock-up more realistic scenario.
> bar = function(a,b) {
... return "pseudo call to someFunction("+a+","+b+")";}
then,
> myArray.forEach(function(e){
... console.log(bar(e[0], e[1]));})
pseudo call to someFunction(-100.5,-1)
pseudo call to someFunction(-200.8,-2)
pseudo call to someFunction(-312.5,-3)
You can convert your array to object hash and use first parameter as object key, like this:
var myObject = {'-100.5': -1,'-200.8': -2,'-312.5': -3};
I've updated example with adding randomizing
var myObject = {'-100.5': -1,'-200.8': -2,'-312.5': -3};
var keys = Object.keys(myObject).sort(function(a, b) {
return Math.random() < Math.random() ? 1 : 0;
});
keys.forEach(function(key) {
console.log(key, myObject[key]);
});

How to use mapping to transfer things to an empty array?

I am trying to pass over the function that is inside of the variable inputOne to the empty array of transferHere
This does not seem to be working. How can I map what is inside of inputOne into transferHere, so that everything is transferred over?
var transferHere = [];
var inputOne = transferHere.map(function(name) {
return (5 * name) - 20;
});
The map function iterates over an array of values and generates a new array of values.
For example:
var arr1 = [1,2,3];
var result = arr1.map(function(val){
return val + 1;
});
//result would be: [2,3,4]
So it seems like you are doing it wrong and your code should be (assuming that
inputOne is an array):
var transferHere= inputOne.map(function(name) {
return (5 * name) - 20;
});
UPDATE:
From the comment i understand that inputOne is a function and you want to put it's actual content (i.e. as a string) in an array, so here is how:
var arr1 = [];
arr1.push(inputOne.toString());

Finding the sum of an array in javascript [duplicate]

This question already has answers here:
How to force JS to do math instead of putting two strings together [duplicate]
(11 answers)
Closed 7 years ago.
I have to write 6 small JavaScript scripts for school and I've got them all working apart from this one.
function calculate() {
var numbers = [
document.getElementById("num_one").value ,
document.getElementById("num_two").value ,
document.getElementById("num_three").value
];
var sum = numbers[0] + numbers[1] + numbers[2];
document.getElementById("display_sum").innerHTML = sum;
}
The user is supposed to enter 3 numbers click a button and it should add them all togther or "find the sum".
My Problem is, it just joins the numbers togther instead of adding them. Does anyone know a way to fix this?
You are "summing" string variables so Javascript is concatenating them.
You need to convert them to numbers in order to have an arithmetic sum:
function calculate() {
var numbers = [
document.getElementById("num_one").value ,
document.getElementById("num_two").value ,
document.getElementById("num_three").value
];
var sum = Number(numbers[0]) + Number(numbers[1]) + Number(numbers[2]);
document.getElementById("display_sum").innerHTML = sum;
}
Parse string using parseFloat(), parseInt() or Number(), for converting it's to number. Otherwise + will just do string concatenation , since the values are string.
function calculate() {
var numbers = [
document.getElementById("num_one").value,
document.getElementById("num_two").value,
document.getElementById("num_three").value
];
var sum = parseFloat(numbers[0]) + parseFloat(numbers[1],) + parseFloat(numbers[2]);
document.getElementById("display_sum").innerHTML = sum;
}
function calculate() {
var numbers = [
document.getElementById("num_one").value,
document.getElementById("num_two").value,
document.getElementById("num_three").value
];
var sum = Number(numbers[0]) + Number(numbers[1]) + Number(numbers[2]);
document.getElementById("display_sum").innerHTML = sum;
}
function calculate() {
var numbers = [
document.getElementById("num_one").value,
document.getElementById("num_two").value,
document.getElementById("num_three").value
];
var sum = parseInt(numbers[0], 10) + parseInt(numbers[1], 10) + parseInt(numbers[2], 10);
document.getElementById("display_sum").innerHTML = sum;
}
The value property is string. In order to use it in arithmetic operations, you need to parse it to integers. The simpliest way to do this in JS is +x. You can use Array.prototype.map and Array.prototype.reduce to make it easier:
var ids = ['num_one', 'num_two', 'num_three'];
var sum = ids
.map(function(x) { return +document.getElementById(x).value; })
.reduce(function(a,b) { return a+b; }, 0);
With this way, you will be able to introduce new elements into calculations with minimal changes.
.value return String you need convert it to Number,
you can do it with parseInt or parseFloat(if you have float values), or with Number() or just add + before value
var numbers = [
+document.getElementById("num_one").value,
+document.getElementById("num_two").value,
+document.getElementById("num_three").value
];
or
var numbers = [
Number(document.getElementById("num_one").value),
Number(document.getElementById("num_two").value),
Number(document.getElementById("num_three").value)
];
or
var numbers = [
parseInt(document.getElementById("num_one").value, 10),
parseInt(document.getElementById("num_two").value, 10),
parseInt(document.getElementById("num_three").value, 10)
];
The shortest approach is to use Array.prototype.map
The map() method creates a new array with the results of calling a provided function on every element in this array.
in combination with Number
The Number JavaScript object is a wrapper object allowing you to work with numerical values. A Number object is created using the Number() constructor.
The primary uses for the Number object are:
If the argument cannot be converted into a number, it returns NaN.
In a non-constructor context (i.e., without the new operator), Number can be used to perform a type conversion.
and then Array.prototype.reduce
The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.
in combination with a callback like
function (a, b) {
return a + b;
}
Together in a single line with your code wrapped:
function calculate() {
var numbers = [
document.getElementById("num_one").value,
document.getElementById("num_two").value,
document.getElementById("num_three").value
],
sum = numbers.map(Number).reduce(function (a, b) { return a + b; });
document.getElementById("display_sum").innerHTML = sum;
}
A scalable solution in one line of es6:
var sum = numbers.reduce((a, b) => Number(a) + Number(b), 0);
Be sure to include an initialValue at the end there - it'll guarantee the callback is executed and a number is returned in cases where the array contains no values/one value.
More info on reduce
Depending on whether your input numbers are integers or decimals, you can use parseInt or parseFloat.
There are already plenty of reasonable answers, but here's a neat shorthand alternative:
var sum = +numbers[0] + +numbers[1] + +numbers[2];
I think you can use an array to store the inputs like
<script>
var numbers;
function push(){
numbers.push(getDocumentById("someid").val;
}
function calculate(){
var sum=0;
for(i=0; i<numbers.len; i++){
sum=sum + numbers[i];
}
alert(sum);
}
</script>
<div>
<button id="someid" value=20 onClick="addToArray();">click to push</button>
</div>
<div>
<button id="calc" onClick="calculate();">click to calculate</button>
</div>
The following will solve the problems:
function calculate() {
var numbers = [
+(document.getElementById("num_one").value) ,
+(document.getElementById("num_two").value) ,
+(document.getElementById("num_three").value)
];
var sum = numbers[0] + numbers[1] + numbers[2];
document.getElementById("display_sum").innerHTML = sum;
}
By default, javascript treats input values as strings. So you have to manually convert them to integers like this:
var numbers = [
document.getElementById("num_one").value ,
document.getElementById("num_two").value ,
document.getElementById("num_three").value
];
document.getElementById("display_sum").innerHTML =
numbers
.reduce(function(sum, element) { return sum + parseInt(element, 10);}, 0);
What is good about this code, is that if you need to calculate for more than three elements you only need to modify your numbers array.

Javascript for-loop returning "null" instead of my value

I'm trying to get the function below to return the average of all elements in array1, but I keep getting null as the result. I can't seem to figure out why.
var array1 = [46,73,-18,0,-442,779,5,1400];
var arrayAverage = function(arrayavg) {
for (var average = 0,answer=0, arrayavg = arrayavg.length;array1 > answer;answer++)
average +=parseInt(arrayavg[answer]);
var calc = average/arrayavg.length;
return calc
};
There are a number of errors, I don't have time to point them all out, hopefully the following is sufficient:
var array1 = [46,73,-18,0,-442,779,5,1400];
var arrayAverage = function(arrayavg) {
I don't know why you using a function expression rather than a function declaration. It doesn't affect the issue, but is more code to write. It's also good to give variables names that express what they are for, so given that the function expects an array:
function arrayAverage(array) {
then:
for (var average = 0,answer=0, arrayavg = arrayavg.length;array1 > answer;answer++)
It's not a good idea to pile all those variable declarations into the for condition, far better to separate concerns and only create variables that you need:
var total = 0;
Now iterate over the array to get the total value. The '{' brackets can be omitted, but it's clearer to include them:
for (var i=0, iLen=array.length; i<iLen; i++) {
total += array[i];
}
Now calculate the average and return it in one statement:
return total/iLen;
}
console.log(arrayAverage(array1)); // 230.375
You need to put brackets after your for loop
I was too fast to answer.
You are re-assigning the passed array to the length of the passed array.
arrayavg = arrayavg.length
this breaks everything.
in the for loop you have assigned arrayavg=arrayavg.length and in the body ,you are accessing average+=arrayavg[answer]. arrayavg is now a primitive type . it will return undefined.
And your loop condition is array1 > answer array1 is an array .you cant compare it like that.it will return false.
modified code.
var array1 = [46,73,-18,0,-442,779,5,1400];
var arrayAverage = function(arrayavg) {
var sum=0;
for (var i=0;i<arrayavg.length;i++)
sum +=parseInt(arrayavg[i]);
return sum/arrayavg.length;
};
You are comparing a number to your array in your for loop. You want to stop the for when answer is the same as array1 length.
Also, don't change your parameter array to its length if you want to get its values in the loop.
var array1 = [46,73,-18,0,-442,779,5,1400];
var arrayAverage = function(arrayavg) {
for (var average = 0,answer=0, len = arrayavg.length;len > answer;answer++)
average +=parseInt(arrayavg[answer]);
var calc = average/len;
return calc
};
And to call it:
arrayAverage(array1);
Your code has two problems in the for loop.
for (var average = 0,answer=0, arrayavg = arrayavg.length;array1 > answer;answer++)
^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^
First thing is you set arrayavg to arrayavg's length BUT in the next line you try to read the index of the array. Well you overwrote the array with a number! Not going to happen.
Second issue you are comparing an array 'array1' to a number 'answer' . What does that check do? Not what you think it is going. You want to be checking the length, but wouldn't you want to be checking the passed in array, not the hardcoded one?
I think the other answers (particularly RobG) have covered most of it. It might help to follow a couple of standard rules (that I use) for your loops:
1) Always have the index as the first declared element, the length of the array (for caching purposes) as the second, and any other variables after them.
2) Always use brackets to separate your loop code from the code in the rest of the function. That way you know when to return your averaged product (ie after the }).
So this is my slightly rewritten code of your problem:
for (var index = 0, len = arrayavg.length, avg = 0; index < len; index++) {
avg += parseInt(arrayavg[index], 10) / len;
}
return avg;
Note also that parseInt should contain a radix (in this case 10). You can leave it out but it's good practice to always include it.
By the way, here's an alternative to your function you might find useful that uses a functional approach using reduce:
var arrayAverage = function (arr) {
return arr.reduce(function (a, b) { return a + b; }) / arr.length;
}

Javascript Functional Programming

I'm confused on why one is returning me the sum while the other one is just returning the list.
This correctly returns the output 10
function sum(){
var arrays = [1,2,3,4].reduce(function (total, num) {
return total + num;
})
console.log(arrays);
}
This however, returns [1, 2, 3, 4] and not 10.
function sum(){
var arrays = [1,2,3,4];
arrays.reduce(function (total, num) {
return total + num;
})
console.log(arrays);
}
At first I thought it's where I was declaring the var arrays so I tried moving it out of the function and also tried not declaring it var. However for this one I'm still not getting 10.
What's the difference between the two that I'm not getting the correct output?
Thanks.
You are missing the assignment, which is returned by the reduce:
function sum() {
var arrays = [1, 2, 3, 4];
arrays = arrays.reduce(function(total, num) {
//-----^
return total + num;
})
console.log(arrays);
}
In the second function you are ignoring the return value from the reduce method. It will correctly calculate the sum, but you don't use it.
Assign the result to the variable as in the first function:
array = arrays.reduce(function (total, num) {
return total + num;
});
However, having the result in the same variable as where the array was makes the code somewhat confusing. You should avoid having a variable change meaning in the middle of the code, so you can use a different variable for the result:
function sum(){
var arrays = [1,2,3,4];
var result = arrays.reduce(function (total, num) {
return total + num;
});
console.log(result);
}
Side note: The term functional programming is used for languages that are based on functional expressions instead of variable state. Just using a function doesn't mean that you are using functional programming.
In first,
when the function return the value i.e. 10 it is getting stored in var arrays and you are printing it.
whereas,
In second,
You declared the var arrays and give it the value [1,2,3,4] then funtion is called, the returned value is not getting stored anywhere and at last you are simply printing the var arrays which is [1,2,3,4]

Categories

Resources