Array average with parameter (...rest) - javascript

I'm trying to write a function to calculate the elements average in an array using the parameter (...rest)
Here what I've tried:
function average(...nums) {
let total = 0;
for (const num of nums) {
total += num;
}
return total / nums.length;
}
console.log(average(2, 6));
console.log(average(2, 3, 3, 5, 7, 10));
console.log(average(7, 1432, 12, 13, 100));
console.log(average());
But the last test returns NaN and I don't know why.

function average(...nums)
{
let total = 0;
for(const num of nums)
{
total +=num;
n= nums.length;
}
return total/n;
}
console.log(average(2, 6));
console.log(average(2, 3, 3, 5, 7, 10));
console.log(average(7, 1432, 12, 13, 100));
console.log(average());

Because you're trying to divide 0 (total) by 0 (nums.length where nums is []), which is NaN in JavaScript.
You can have a check at the top of your function that returns a default value (say, 0), if the list is empty:
function average(...nums) {
if (!nums.length) return 0;
let total = 0;
// rest
}

function average(...inputs) {
let avg = 0;
let sum = 0;
for(const input of inputs){
sum += input;
count= inputs.length;
}
avg = sum / count;
return avg;
}
console.log(average(2, 6));
console.log(average(2, 3, 3, 5, 7, 10));
console.log(average(7, 1432, 12, 13, 100));
console.log(average());

You are returning 0/0 (which is NaN) when you pass nothing in, as nums becomes an empty array. and its length becomes 0.
You should return nums.length ? total/nums.length : 0;

Check it the argument which is an array exists, if not return 0 or some value stating that average cannot be calculated.
function average(...nums) {
if (!nums.length) {
return 'Cannot find average'
}
let total = 0;
for (const num of nums) {
total += num;
}
return total / nums.length;
}
console.log(average(2, 6));
console.log(average(2, 3, 3, 5, 7, 10));
console.log(average(7, 1432, 12, 13, 100));
console.log(average());

Related

Javascript Challenge: Loops - Multiple Conditions - stuck and can't figure this out

I did this module on functions and execution context - all questions have gone well but there is one challenge I have spent a lot of time on and still can't figure it out. Any help will be greatly appreciated. Thank you
Challenge question says:
Write a function addingAllTheWeirdStuff which adds the sum of all the odd numbers in array2 to each element under 10 in array1.
Similarly, addingAllTheWeirdStuff should also add the sum of all the even numbers in array2 to those elements over 10 in array1.
BONUS: If any element in array2 is greater than 20, add 1 to every element in array1.
// Uncomment these to check your work!
// console.log(addingAllTheWeirdStuff([1, 3, 5, 17, 15], [1, 2, 3, 4, 5])); // expected log [10, 12, 14, 23, 21]
// console.log(addingAllTheWeirdStuff([1, 3, 5, 17, 15, 1], [1, 2, 3, 4, 5, 22])); // expected log [11, 13, 15, 46, 44, 11]
// my attempt so far:
function addingAllTheWeirdStuff(array1, array2) {
// ADD CODE HERE
let result = []
for (let i = 0; i < array2.length; i++) {
if (array2[i] > 20) {
result = array1[i] += 1
}
}
for (let i = 0; i < array2.length; i++) {
if (array2[i] % 2 === 0 && array1[i] > 10) {
result = array1[i] + array2[i]
}
}
for (let i = 0; i < array2.length; i++) {
if (array2[i] % 2 !== 0 && array1[i] < 10) {
result = array1[i] + array2[i]
}
}
return result
}
You can easily achieve this using reduce and map array method, with the ternary operator:
const array1 = [1, 3, 5, 17, 15];
const array2 = [1, 2, 3, 4, 5];
function addingAllTheWeirdStuff(array1, array2) {
const oddSum = array2.reduce((sum, current) => current % 2 ? current + sum : 0 + sum, 0)
const oddEven = array2.reduce((sum, current) => current % 2 == 0 ? current + sum : 0 + sum, 0)
return array1.map(num => num < 10 ? num + oddSum : num + oddEven)
}
console.log(addingAllTheWeirdStuff(array1, array2))
If you break the challenge into smaller pieces, you can deconstruct it better and come up with your solutions.
This is what I did... I will be adding more comments shortly with more explanations
I chose to keep using loops as I assumed this was the point of the challenges (to practice for loops, multiple conditions, etc) - In other words, I chose to not use map / reduce on purpose but if that's allowed, use the answer by #charmful0x as it results in less code :)
// function to get sum of all odd numbers in array
function getSumOfAllOddNumbersInArray( elementArray ){
var sumOfOddNumbers = 0;
for (let i = 0; i < elementArray.length; i++) {
// use remainder operator to find out if element is odd or not
if (elementArray[i] % 2 !== 0 ) {
sumOfOddNumbers += elementArray[i];
}
}
return sumOfOddNumbers;
}
// function to get sum of all EVEN numbers in array
function getSumOfAllEvenNumbersInArray( elementArray ){
var sumOfEvenNumbers = 0;
for (let i = 0; i < elementArray.length; i++) {
// use remainder operator to find out if element is odd or not
if (elementArray[i] % 2 === 0 ) {
sumOfEvenNumbers += elementArray[i];
}
}
return sumOfEvenNumbers;
}
// Return true if there is at least one element in array that is greater than 20
function hasElementOverTwenty( elementArray ){
for (let i = 0; i < elementArray.length; i++) {
if (elementArray[i] > 20 ) {
// no need to keep looping, we found one - exit function
return true;
}
}
return false;
}
function addingAllTheWeirdStuff( firstArray, secondArray ){
var sumOfOddNumbersInArray = getSumOfAllOddNumbersInArray( secondArray );
var sumOfEvenNumbersInArray = getSumOfAllEvenNumbersInArray( secondArray );
var needToAddOne = hasElementOverTwenty( secondArray );
for (let i = 0; i < firstArray.length; i++) {
// Challenge One
if (firstArray[i] < 10) {
firstArray[i] = firstArray[i] + sumOfOddNumbersInArray;
} else if (firstArray[i] > 10) {
// Challenge Two
firstArray[i] = firstArray[i] + sumOfEvenNumbersInArray;
}
// bonus
if( needToAddOne ){
firstArray[i]++;
}
}
return firstArray;
}
// Uncomment these to check your work!
console.log(addingAllTheWeirdStuff([1, 3, 5, 17, 15], [1, 2, 3, 4, 5]));
console.log('expected:' + [10, 12, 14, 23, 21] );
console.log(addingAllTheWeirdStuff([1, 3, 5, 17, 15, 1], [1, 2, 3, 4, 5, 22]));
console.log('expected:' + [11, 13, 15, 46, 44, 11] );
Challenge question says: Write a function addingAllTheWeirdStuff which adds the sum of all the odd numbers in array2 to each element under 10 in array1.
Similarly, addingAllTheWeirdStuff should also add the sum of all the even numbers in array2 to those elements over 10 in array1.
BONUS: If any element in array2 is greater than 20, add 1 to every element in array1.

Multiplying array numbers sequentially

The best and the easiest way to multiply array numbers sequentially
I have got an array with some values:
const arr = [1, 5, 12, 3, 83, 5];
Now I want to get the product of all values from arr. It should works like this: 1 * 5 * 12 * 3 * 83 * 5
I have tried with this code:
const arr = [1, 5, 12, 3, 83, 5];
multiply(arr);
function multiply(arr) {
for(i = 0; i < arr.length; i++) {
product = array[i] * array[i];
console.log(product);
}
}
This code above works like this: 1 * 1, 5 * 5, 12 * 12, 3 * 3, 83 * 83, 5 * 5 and that is not result that I need. I think I know why it works like this but I'm not sure how to write code that I need.
So what's the best option for this kind of tasks?
Edit.
For non-experienced people looking here in future this is the best option that we've found:
Leo Martin answer:
const array = [1, 5, 12, 3, 83, 5];
console.log(multiply(array)); // we log function return value
function multiply(array) {
let score = array[0];
for (i = 1; i < array.length; i++) {
score = score * array[i];
}
return score;
}
and also the shorter version:
By the way, you could use Array.reduce:
const array = [1, 5, 12, 3, 83, 5];
const result = array.reduce((acc, value, index) => {
if (index === 0) return value;
acc = acc * value;
return acc;
}, 0);
console.log(result);
Just move console.log outside for body:
const array = [1, 5, 12, 3, 83, 5];
console.log(multiply(array)); // we log function return value
function multiply(array) {
let score = array[0];
for (i = 1; i < array.length; i++) {
score = score * array[i];
}
return score;
}
By the way, you could use Array.reduce:
const array = [1, 5, 12, 3, 83, 5];
const result = array.reduce((acc, value, index) => {
if (index === 0) return value;
acc = acc * value;
return acc;
}, 0);
console.log(result);
You can use reduce method to multiply all numbers
const array = [1, 5, 12, 3, 83, 5];
const total = array.reduce((total,num) => total * num, 1);
console.log(total)
Corrected your program.
const array = [1, 5, 12, 3, 83, 5];
multiply(array);
function multiply(array) {
var score = 1;
for(i = 0; i < array.length; i++) {
score = score * array[i];
}
console.log(score);
}
Hope the solution is self explanatory. Loop through array. Multiply each product and store the result in the same variable.
const array = [1, 5, 12, 3, 83, 5];
multiply(array);
function multiply(array) {
let product = 1;
for(i = 0; i < array.length; i++) {
product *= array[i];
}
console.log(product);
}
const array = [1, 5, 12, 3, 83, 5];
multiply(array);
function multiply(array) {
var score = array[0];
for(i = 1; i < array.length; i++) {
score = score * array[i];
}
console.log(score);
}
var array = [1, 5, 12, 3, 83, 5];
var result = array.reduce(function(a, b) {
return a * b;
});
console.log(result);
const array = [1, 5, 12, 3, 83, 5];
multiply(array);
function multiply(array) {
for(i = 0; i < array.length-1; i++) {
score = array[i] * array[i+1];
console.log(score);
}
}
For the calculation of the final result of multiply:
const array = [1, 5, 12, 3, 83, 5];
multiply(array);
function multiply(array) {
score = 1;
for(i = 0; i < array.length; i++) {
score = score * array[ i ];
}
console.log(score); // expected result: 74700
}
Are you asking for a textual representation of the calculations? If so, use this:
const array = [1, 5, 12, 3, 83, 5];
multiply(array);
function multiply(array) {
score = '';
for(i = 0; i < array.length; i++) {
score += array[i].toString();
if ( i < array.length -1 ) score += '*';
}
console.log(score); // expected result: '1*5*12*3*83*5'
}
This should start to put you on the right way, hope it helps.
score = array[i] * array[i]; you are trying to multiply exact exp-rations.
const array = [1, 5, 12, 3, 83, 5];
its like: 1*1, 5*5
you can multiply array[i] * i
another approach might be an array function.
const array = [1, 5, 12, 3, 83, 5];
multiply(array);
function multiply(array) {
let product = 1;
`enter code here`for(i = 0; i < array.length; i++) {
product *= array[i];
}
console.log(product);
}
let multiArray = array.map((num, index) => num *index)
console.log(multiArray)
for more info:https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Global_Objects/Array/map.

Avoid using nested loops to find the max-sized sub-string of an array?

Added maximum number according to the input length should be returned.
For example, if the length is 2 then the max among arr[0] + arr[1], arr[1] + arr[2], arr[2] + arr[3] should be returned.
Input is array and length.
I solved this in a real job interview but I think there will be a way not to use nested loop.
const add = (arr, len) => {
let rtnVal = 0
for (let i = len - 1; i < arr.length; i++) {
let temp_idx = i;
let temp_sum = 0;
for (let j = 0; j < len; j++) {
temp_sum = (temp_sum || 0) + arr[temp_idx]
temp_idx -= 1
}
if (temp_sum > rtnVal) {
rtnVal = temp_sum
}
}
return rtnVal
}
console.log(add([1, 2, 3, 4, 5, 6, 7, 8, 9], 4))
I expect the output 30
// enhanced nested loop
const add = (arr, len) => {
let rtnVal = 0;
for(let i=len-1;i<arr.length;i++){
let sum = 0
for(let j=i;j>=i-len+1;j--){
sum += arr[j]
}
if (sum > rtnVal) rtnVal = sum
}
return rtnVal
}
console.log(add([9, 9, 9, 4, 5, 6, 7, 8, 9], 3))
Use a moving window. Add up len numbers starting at the beginning. Then continue through the array adding the next number and subtracting the trailing number.
const add = (arr, len) => {
return arr.reduce((a,v,i,arr) => {
a.running += v;
if(i >= len) {
a.running -= arr[i-len];
}
if(i+1 >= len && a.largest < a.running) {
a.largest = a.running;
}
return a;
}, {
largest: Number.NEGATIVE_INFINITY,
running: 0
}).largest;
}
console.log(add([1,2,3,4,5,6,7,8,9],4)); // 30
console.log(add([-1,-1,-1,-1],2)); // -2
console.log(add([1],1)); // 1
Assuming its sorted like your example. You can use negative slice to select from end and then reduce the array.
const add = (arr, len) => arr.slice(len > arr.len ? arr.len : -len).reduce((total, num) => total + num)
console.log(add([1, 2, 3, 4, 5, 6, 7, 8, 9], 4))

Sorting an increasing number in an array in Javascript

I'm running into a error in stopping the execution when a lower number occurs in the data of an array
Let seat1 = [2, 5, 6, 9, 2, 12, 18];
console should log the values till it gets to 9 since
2 < 5 < 6 < 9
then omit 2 since 9 > 2
then continue from 12 < 18.
let num = [2, 5, 6, 9, 2, 12, 18];
for (let i = 0; i < num.length; i++) {
if ((num[i] + 1) > num[i]) {
console.log(num[i])
} else {
console.log('kindly fix')
}
}
Use Array.reduce() to create a new array without the items that are not larger than the last item in the accumulator (acc) or -Infinity if it's the 1st item:
const num = [2, 5, 6, 9, 2, 3, 12, 18];
const result = num.reduce((acc, n) => {
if(n > (acc[acc.length - 1] || -Infinity)) acc.push(n);
return acc;
}, []);
console.log(result);
simple answer using if and for -
let num = [2, 5, 6, 9, 2 , 3, 12, 16, 9, 18];
let max = 0;
for (let i = 0; i < num.length; i++)
{
if ((i == 0) || (num[i] > max)) {
max = num[i];
console.log (num[i]);
}
}
You could filter the array by storing the last value who is greater than the last value.
var array = [2, 5, 6, 9, 2, 3, 12, 18],
result = array.filter((a => b => a < b && (a = b, true))(-Infinity));
console.log(result)
Store the max value and check num[i] against the current max. If num[i] is bigger, log it and set the new max value. Initial max value should be first num value but smaller so it doesn't fail on the first check.
let num = [2, 5, 6, 9, 2, 12, 18];
let max = num[0] - 1;
for (let i = 0; i < num.length; i++) {
if (num[i] > max) {
console.log(num[i]);
max = num[i];
}
}
let num = [2, 5, 6, 9, 2, 12, 18];
let result = num.sort((a, b) => a - b).filter((elem, pos, arr) => {
return arr.indexOf(elem) == pos;
})
console.log(result)

Sum Function with array argument

i'm starting studying javascript. I'm stuck with this exercise: Create a function that takes an array as argument and return the sum of all elements of the array.
I have written this code:
function sum(table) {
let x = table[0];
let y = [table.length - 1];
let totale = 0;
for (count = x; count <= y; count++) {
total += x;
x += 1;
};
return total;
};
console.log(sum[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
I don't know why the result is undefined instead of 55. Thanks for helping.
total not totale
the function call needs parentheses as sum([…])
y = table.length - 1 you want the length, not an array that holds the length
x = 0 you don't need to set it to the first element of the array
total += table[count]; you don't need to set it to x or to deal with x at all
function sum(table) {
let x = 0;
let y = table.length - 1;
let total = 0;
for (count = x; count <= y; count++) {
total += table[count];
};
return total;
};
console.log(sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
Quicker Solution
function sum(table) {
return table.reduce((p,c)=>p+c,0);
};
console.log(sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
Here are couple of things.
You need to execute the sum function by calling like sum([array elements]) .Note the ( & ) braces
Secondly count <= y will give undefined as it will exceed the length of the array. The array index starts from 0;
There is a typo here totale.
You can avoid these set of lines
let x = table[0];
let y = [table.length - 1];
if you just initialize the loop conditional statement like this
for (let count = 0; count < table.length; count++)
function sum(table) {
let x = 0
for (let count = 0; count < table.length; count++) {
x += table[count];
};
return x;
};
console.log(sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
Another option is to use the reduce method
function sum(table) {
return table.reduce(function(acc, curr) {
return acc += curr;
}, 0) // 0 is the initial value
};
console.log(sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));

Categories

Resources