Passing array as argument to a js function - javascript

I wanted to create a basic function summing up values from an array. I'm aware of the array reduce method but i wanted initially to use a loop "for" instead as below...however it returns NaN...why ?
var numbers=[1,2];
var total;
function sum(array){
total=0;
for(var x=0;x<=array.length;x++){
total += array[x];
}
return total;
}

Do sum(numbers), also in your loop the break condition should be x<array.length; also you do not need to make total a global variable to continue adding values of array to it.
var numbers = [1, 2];
function sum(array) {
var total = 0;
for (var x = 0; x < array.length; x++) {
total += array[x];
}
return total;
}
var total = sum(numbers);
alert(total);
Though the shorter way will be to use .reduce on the array
var array = [1,2]
var sum = array.reduce(function(prev, curr) { return prev + curr; }, 0);
alert(sum);
Here You can also provide an Arrow Function instead of a full function.
var array = [1, 2]
var sum = array.reduce((prev, curr) => prev + curr);
alert(sum);

You get NAN because, as the loop's condition isx<=array.length, the last iteration adds array[length] to the sum, while the last item of the array is array[length - 1]

You could also use reduce to sum up all elements:
sum = array.reduce(function(a, b) { return a + b; }, 0);

If you want to stay on your initial approach, then you don't have to return global variable from within function. You can change global variables inside function directly;
var numbers=[1,2],
total;
function sum(array){
total=0;
for(var x = 0, len = array.length; x < len; x++){
total += array[x];
}
}
In other cases, of course, using of local variables is preferable when you intend to form independent results

Related

Javascript reduce not working after function?

Not too sure where I've gone wrong here, expecting to factorialize 5 (1*2*3*4*5 = 120) by turning 5 into a string of [1,2,3,4,5] and then using reduce to multiply the string all together. When I run the code, it just gives me [1,2,3,4,5]...
var arr = [];
function factorialize(num) {
for (var i = 1; i <= num; i++) {
arr.push(i);
}
return arr;
}
var factors = 0;
factors = arr.reduce(function(previousVal, currentVal) {
return previousVal * currentVal;
}, 0); // Expecting 120, instead result = [1,2,3,4,5]
factorialize(5);
Forgive the long route - my first week of Javascript!
arr is empty, you should give it the resulting array of the factorisation first, and you should multiply, not add, and when multiplying, the starting value is 1 not 0:
var arr = [];
function factorialize(num) {
for (var i = 1; i <= num; i++) {
arr.push(i);
}
return arr;
}
arr = factorialize(5); // give it the value
var factors = arr.reduce(function(previousVal, currentVal) {
return previousVal * currentVal; // multiply, don't add
}, 1); // start with 1 when multiplying
console.log(arr);
console.log(factors);
If you just want to calculate the factorial:
function factorial(num) {
var res = 1;
for (var i = 2; i <= num; i++) {
res *= i;
}
return res;
}
console.log('factorial(5) = ' + factorial(5));
console.log('factorial(10) = ' + factorial(10));
You are not calling factors. factorialize(5); by doing this you are just calling function factorialize(num) which will give you array(of 1...num).
(Additional info)And also in reduce you are adding + instard of multiplying * so change that too and
factors = arr.reduce(function(previousVal, currentVal) {
return previousVal + currentVal;
}, 0);
^
|_ either initialize it to 1 or remove this.
See below code. I just create array and then apply reduce on that array.
function factorialize(num) {
var arr = [];
for (var i = 1; i <= num; i++) {
arr.push(i);
}
return arr.reduce(function(previousVal, currentVal) {
return previousVal * currentVal;
});
}
console.log(factorialize(5));
var arr = [];
function factorialize(num) {
for (var i = 1; i <= num; i++) {
arr.push(i);
}
var factors = 0;
factors = arr.reduce(function (previousVal, currentVal) {
return previousVal * currentVal;
});
return factors
}
factorialize(5); // 120
You could get first the factors and then multiply in Array#reduce the factors.
I suggest to name the function what it does and move the array declaration inside of the function, because the function returns this array.
For getting the product, you need to multiply the values and use 1 as neutral start value for getting a product out of the numbers.
function getFactors(num) {
var i, arr = [];
for (i = 1; i <= num; i++) {
arr.push(i);
}
return arr;
}
var factors = getFactors(5),
product = factors.reduce(function(previousVal, currentVal) {
return previousVal * currentVal;
}, 1);
console.log(factors);
console.log(product);
Put the global variable arr inside of the function factorialize.
Get the returned array and then execute the function reduce.
You need to multiply rather than to add the numbers.
Start the reduce with initialValue = 1, this is to avoid 0 * n.
function factorialize(num) {
var arr = [];
for (var i = 1; i <= num; i++) {
arr.push(i);
}
return arr;
}
var arr = factorialize(5);
var factors = arr.reduce(function(previousVal, currentVal) {
return previousVal * currentVal;
}, 1);
console.log(factors)
Issue is with the initial value set to 0 and instead of multiplying numbers, it is being added
arr.reduce(callback, initValue)
arr = [1,2,3,4,5]
In the code provided, it accumulates in below format
arr.reduce(function(previousVal, currentVal) {
return previousVal + currentVal;
}, 0);
First call -> 0 + 1 = 1 (factors = 1)
Second call -> 0 + 2 = 2 (factors = 2)
First call -> 0 + 3 = 3 (factors = 3)
First call -> 0 + 4 = 4 (factors = 10)
First call -> 0 + 5 = 5 (factors = 15)
To achieve expected result, use below option
var arr = []; // initialize array arr
function factorialize(num) {
//for loop to push 1,2 ,3, 4, 5 to arr array
for (var i = 1; i <= num; i++) {
arr.push(i);
}
// return arr.reduce value by multiplying all values in array, default initial value is first element
return arr.reduce(function(previousVal, currentVal) {
//console log to debug and display loop values
console.log(previousVal, currentVal);
return previousVal * currentVal;
});
}
console.log("output", factorialize(5));
code sample - https://codepen.io/nagasai/pen/YaQKZw?editors=1010

Picking more than one random from an array

I wrote this function:
function randomProduct(num) {
var iter = num;
for (var i = 0; i < iter; i++) {
var rand = recommendedProducts[Math.floor(Math.random() * recommendedProducts.length)];
return rand
}
}
Which is supposed to pull from the recommendedProducts array however many are needed when the function is called. So basically randomProduct(1) would pull 1 and randomProduct(4) would pull 4, etc.
However no matter what number I enter in there when I test is through the console, I always only get 1 array item returned.
console.log(randomProduct(1));
console.log(randomProduct(2));
console.log(randomProduct(3));
console.log(randomProduct(4));
What am I doing wrong?
try this:
function randomProduct(num) {
var iter = num;
var rand ="";
for (var i = 0; i < iter; i++) {
rand += recommendedProducts[Math.floor(Math.random() * recommendedProducts.length)];
}
return rand
}
as #Steve Medley said the result expected to be string. so if recommendedProducts contains some string you should add this string in each iteration of loop to your result and return it after your loop has finished( also this is what i have understood from question)
Try this:
function randomProduct(num) {
var iter = num;
var randomArray = [];
for (var i = 0; i < iter; i++) {
randomArray.push(recommendedProducts[Math.floor(Math.random() * recommendedProducts.length)]);
}
return randomArray.join(); // returns it as a string
}
First you need to append the items to an array using push
Second you need to return outside of the loop, if you retrun from the inside of the loop you break the function after the first iteration.
The return rand take you off the function at the first result.
You can remove the loop, just return the rand, and call the function 4 times.
If you want the function to return array of random numbers, instead of return rand, push the results to new array and return the array when the for loop is done.
In your loop, variable rand will be given the value equal to the value it's last iterations output, you need to return array of objects instead of single object to get desired result.

Define a function that contains an unknown function in javascript

i was asked to define a function reduce, that has three parameters, an array, an unknown function, and a number, and reduces the array into a number
and this is was i was given before i was asked to define the function
reduce([1, 2, 3], function(total, number) {
return total + number;
}, 0); // should return 6
I am a bit clueless on what this is asking me to do to be completely honest
if i could at least get some guideline id be grateful
here is my attempt
var reduce = function(array, func, initial){
function func(){
}
for( var i = 0; i < array.length; i++){
func(initial, array[i]);
}
}
Try:
function reduce(list, f, acc) {
return list.length ?
reduce(list.slice(1), f, f(acc, list[0])) :
acc;
}
Simple.
You need to be sure to create a total variable which will be redefined after every function call. You were very close. Try this out:
var reduce = function(array, func, initial){
var total = initial,
arr_len = array.length;
for(var i = 0; i < arr_len; i++){
total = func(total, array[i]);
}
};

why does assigning a number to an array make the array object a nan?

I have the following code:
function bytesToMb(arr)
{
for(var i=0;i<arr.length;arr++)
{
var mbs= arr[i]/(1000*1000);
arr[i]=mbs;
}
return arr;
}
after the line arr[i]=mbs executes, the value of arr (the array object itself) becomes NAN.
why is that????
You are incrementing arr, arr + 1 = NaN because array is NaN; you ought to do i++ in your for loop instead...
You're using arr++ instead of i++ as the third clause in your for loop.
The type coercion from Array to Number leads to your NaN.
Change arr++ to i++
function bytesToMb(arr) {
for (var i = 0; i < arr.length; i++) {
var mbs = arr[i] / (1024 * 1024); // you should use 1024*1024 here to make it more precise if you need to.
arr[i] = mbs;
}
return arr;
}

checking if sum of array is greater than max number and vice versa javascript

function ArrayAdditionI(arr) {
var numbers = arr();
var arraySum = "";
for (var i = 0; i < numbers.length; i++) {
arraySum = arraySum + arr[i];
};
if (numbers.max() <= arraySum) {
arr = true
}
else if (numbers.max() > arraySum) {
arr = false;
}
return arr;
}
I need to find the numbers stored in an array called arr and check if they add up to or total the greatest number or whether they do not. If so, return true. If not, return false.
I am not sure I am calling the array correctly in the beginning.
Thanks
I actually wrote a library I use just for functions like this.
http://code.google.com/p/pseudosavant/downloads/detail?name=psMathStats.min.js
You would just do this:
var arr = [1,2,3,4,5,300];
if (arr.max() > arr.sum()){
// Max is greater than sum...
}
One warning though. This library prototypes the Array object which could mess up other scripting that uses for (var i in arr) on an Array, which you shouldn't ever do. I am actually almost done with v2 of the library with a number of new functions and it no longer prototypes the Array object.
You can just grab the .max() and .sum() methods from the code, and use them without the prototyping if you want though.
maxArray = function (arr) {
return Math.max.apply(Math, arr);
}
sumArray = function (arr) {
for (var i = 0, length = arr.length, sum = 0; i < length; sum += arr[i++]);
return sum;
}
You mean something like this?
function ArrayAdditionI(arr) {
for (var i = 0, sum=0; i < arr.length; i++) {
sum += arr[i];
}
return Math.max.apply( Math, arr ) <= sum;
}
function ArrayAdditionI(input) {
var arraySum, max;
arraySum = max = input[0];
for (var i = 1; i < input.length; i++) {
arraySum += input[i];
if(input[i] > max){
max = input[i];
}
};
return arraySum >= max;
}
If the numbers are positive, the answer is guaranteed - the sum is always greater than or equal to the max. If you need to calculate it, ddlshack's code looks good.
Looking at your code, there are a number of issues. First of all, arr() should error out. Arrays aren't functions, and trying to treat them as a function does nothing. Your array is already usable when it is passed in. Additionally, you want to initialize arraySum to 0, not "". The way you are doing it, the values in the array will be coerced into strings and concatenated together, which is not what you are looking for. Finally, arrays don't implement a max() method, but Math does, and functions/methods in javascript can be applied to an array in the manner shown by ddlshack and others.
There are some syntax errors: type missmatch, wrong assign and calls to method that doesn't exists. If I'm understanding what do you want to do, this is the correct code(if changing items order is not a problem):
function ArrayAdditionI(arr) {
var ret = false;
var arraySum = 0;
for (var i = 0; i < arr.length; i++) {
arraySum += arr[i];
}
if (arr.sort()[arr.length-1] <= arraySum) {
ret = true
}
return ret;
}

Categories

Resources