Sum Function with array argument - javascript

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]));

Related

Resetting index in a for loop

This function needs to find the first occurrence of consecutive numbers whose sum equals 10, and return them as an array. My idea was to keep summing the numbers until the accumulator, in this case x becomes greater than 10, at which point the value of x is reset to zero, and i is reset back to index 1, by being assigned to the ct variable that is supposed to grow by one on each reset, so the loop would go back and start at the next element, until it gets the correct value. But for some reason ct is stuck at 1 and doesn't grow and the loop doesn't move past the second array element at index 1. Is there an error in the logic or the implementation?
Warning: This code may cause the page to crash or become unresponsive
const arr = [2, 3, 1, 2, 7, 2, 5, 4, 5, 1, 2, 1];
function test(arr) {
let x = 0;
for (let i = 0; i < arr.length; i++) {
let ct = 0;
x = x + arr[i]
if (x > 10) {
x = 0;
i = ct;
ct++
}
console.log(x)
}
}
console.log(test(arr))
The problem is that you've defined ct in the wrong place. It's inside the loop, meaning that every time you get to a point where i = ct, i is reset to 0 and ct++ has no effect (because every iteration, ct is reset to 0). You need to define ct in the same scope as x:
const arr = [2, 3, 1, 2, 7, 2, 5, 4, 5, 1, 2, 1];
function test(arr) {
let x = 0;
let ct = 0;
for (let i = 0; i < arr.length; i++) {
x = x + arr[i];
if (x > 10) {
x = 0;
i = ct;
ct++;
}
console.log(x);
}
}
test(arr);
I've also filled in the rest of the logic of the function for you in case you'd like it:
const arr = [2, 3, 1, 2, 7, 2, 5, 4, 5, 1, 2, 1];
function test(arr) {
let x = 0;
let ct = 0;
let result = [];
for (let i = 0; i < arr.length; i++) {
x = x + arr[i];
if (x > 10) {
x = 0;
i = ct;
ct++;
}
if (x == 10) {
result = arr.slice(ct, i + 1);
return result;
}
console.log(x);
}
return result;
}
console.log(test(arr));

How can I push a number into an array?

I've been trying to push a number after the "for loop" into "x" but I cant use "x += count.push()" because it's not an array.
function partsSums(ls) {
let count = 0;
let x = []
while (ls.length > 0) {
for (let i = 0; i < ls.length; i++) {
count += ls[i]
}
x += count;
count = 0;
ls.shift()
}
return x;
}
console.log(partsSums([0, 1, 3, 6, 10]));
I need to get x = [20, 20, 19, 16, 10, 0] and I'm getting 2020191610 instead.
I'm pretty sure this is a no-brainer but I seem to be missing something...
You could reduce from the right.
function partsSums(array) {
return array.reduceRight((r, v) => [v + r[0], ...r], [0]);
}
console.log(partsSums([0, 1, 3, 6, 10]));

Array average with parameter (...rest)

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());

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)

Adding an element to an array from inside a for loop

in the for loop below I have arr[i] = x * i; I am basically trying to get multiples of numbers. the results of the code I have now is [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] I do not want the first element of the array to be 0 ..
var n = 10;
var arr = [];
var x = 2;
for(var i = 0; i < n; i++ ){
//arr[0] = x;
arr[i] = x * i;
// arr.push(x += x)
}
console.log(arr)
i want to be able to do arr[0] and see x. In this case that would be 2 (the number for the multiples..I don't know math words) [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
I know that the problem is that 2 * 0 is equal to 0 so arr[0] = 0. what is the best way to make it so that the first element will be the second loop. I was thinking about making an if statement. or using an array method that slices of the beginning of the array. I hope there is an easier way like changing the for loop.
There are two simple ways to fix this
Change the loop starting value
var arr = [],
x = 2,
n = 10;
for (var i = 1; i <= n; i++) { // Start with `1`
arr.push(x * i);
}
Or, multiply with the next value of i,
var arr = [],
x = 2,
n = 10;
for (var i = 0; i < n; i++) {
arr.push(x * (i + 1)); // Multiply with i + 1
}
If you still want to solve it with array index assignment, then just remove the first element, with Array.prototype.slice after creating the entire array, like this
var n = 10,
arr = [],
x = 2;
for (var i = 0; i <= n; i++) { // Note the limits, 0 to <= n
arr[i] = x * i;
}
console.log(arr);
// [ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 ]
arr = arr.slice(1);
console.log(arr);
// [ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 ]

Categories

Resources