Write a sum() function that takes an array of numbers - javascript

Can someone please explain to me what I am doing wrong here...
This code is from eloquent javascript and it works fine
function sum(array) {
let total = 0;
for (let value of array) {
total += value;
}
return total;
}
And this is what I wrote for the exercise but returns NaN..
function sum(numArray) {
let add = 0;
for (let a = 0; a <= numArray.length; a++) {
let addIndex = numArray[a];
add += addIndex;
}
return add;
}

Your for loop goes out of array indexes. You have to use:
a < numArray.length
Instead of:
a <= numArray.length

You simply add undefined to add, because you run the index count to long.
for (let a = 0; a <= numArray.length; a++) {
// ^ wrong, takes last index + 1
function sum(numArray) {
let add = 0;
for (let a = 0; a < numArray.length; a++) {
let Addindex = numArray[a];
add += Addindex;
}
return add;
}
console.log(sum([1, 2, 3, 4]));

The issue is because of this a <= numArray.length. Change it to a < numArray.length. This case a[5] that is the 6th element or the element at 5th index is undefined as the array starts from 0 index. So it will add an undefined with previously added number and hence it will be NaN
function sum(numArray) {
let add = 0;
for (let a = 0; a < numArray.length; a++) {
let Addindex = numArray[a];
add += Addindex;
}
return add;
}
console.log(sum([1, 2, 3, 4, 5]))

You're getting an out-of-bounds error. In your for loop, you can change it to:
for (let a = 0; a < numArray.length; a++) {
OR
for (let a = 0; a <= numArray.length - 1; a++) {
The latter works too, but is harder to read.

You can also write a function that has two parameters, an array and a callback function that adds the values of the array like
function forEach(array, arrayAdder){
for (var i = 0; i < array.length; i ++)
arrayAdder(array[i]) ;
}
We can now initialize both the array and the sum like
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], sum = 0;
After that we pass it into the function like this
forEach(array, function(number){
sum += number ;
});
Then print the answer
console.log(sum);

Related

Unexpected , value gives me an undefined answear

I am trying to solve a problem , Two Sum for those who know it , I started learning JavaScript coming from Lua , and I am stuck , I don't know why the function returns "undefined" I fill like the variable is defined
var num = [2, 7, 11, 15]
function numbers(target) {
var idx = {}
num.forEach(function(n, i) {
var j = idx[target - n]
if (j) {
var res = '[ ${j} ${i} ]'
return res
}
console.log(n)
idx[n] = i
})
}
console.log(numbers(9))
output:
2
7
11
15
undefined
Problem: https://leetcode.com/problems/two-sum/
I found the solution I think , I don't think it's the best one , but it works
Code:
var nums = [2,7,11,15]
var twoSum = function(target) {
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return [i, j]
}
}
}
}
console.log(twoSum(9))
You have a few issues:
Your current code is returning a string '[ ${j} ${i} ]', you need to return an array [j, i].
Using return from within .forEach() does not return from your numbers function, it instead returns from the inner callback function function(n, i) { which doesn't do much except just skips to the next item in the loop. You need to change your forEach() to a regular for loop so that when you return you return from your numbers function, and not an inner callback.
Your condition if (j) { is flawed. Consider if j is 0, which occurs when the number you're after to add to the current number n is at index 0. In this case, your if-block won't run because 0 is considered falsy. Your condition should instead be more specific by checking that it returned a value if(j !== undefined). See this answer for more details about the condition.
You should be passing nums into your numbers() function rather than relying on a global variable to exist for your function to work correctly.
Example of modified code:
function numbers(nums, target) {
const idx = {}
for(let i = 0; i < nums.length; i++) {
let n = nums[i];
let j = idx[target - n]
if (j !== undefined) {
return [j, i];
}
idx[n] = i;
}
}
console.log(numbers([2, 7, 11, 15], 9));
console.log(numbers([3,2,4], 6));
console.log(numbers([3,3], 6));
See the answers for this question for more details for solving this problem.
var twoSum = function(nums, target) {
let newArr = nums
let sum = 0
outputArr = []
for(let i = 0 ; i < nums.length ; i++){
let val1 = nums[i]
for(let j = 0 ; j < newArr.length ; j++){
if(i !==j) {
let val2 = newArr[j]
if(val1 + val2 === target) {
sum = val1 + val2
outputArr.push(i)
outputArr.push(j)
break;
}
}
}
if(sum === target)
break;
}
return outputArr
};
try this If helps and you need explanation I will help you

for loop inside a function being called in another function's for loop javascript

I'm trying to implement selection sort with javascript, but it seems that either i'm missing something or doing something absolutely wrong.
as you may understand from a first look, sortArray() seems to return arr with only one value 5 while it should return an array with as such [5,5,5,5,5,5].
worth mentioning is that when I comment line smallest_index = find_smallest(nums)
I get the supposed input; [5,5,5,5,5,5].
let nums = [2, 1, 3, 4, 5, 6];
function sortArray(nums) {
let arr = new Array();
let smallest_index;
for (i = 0; i < nums.length; i++) {
smallest_index = find_smallest(nums);
arr.push("5");
}
return arr;
}
function find_smallest(arr) {
let smallest = arr[0];
let smallest_index = 0;
for (i = 1; i < arr.length; i++) {
if (arr[i] < smallest) {
console.log("this");
smallest = arr[i];
smallest_index = i;
}
}
return smallest_index;
}
console.log(sortArray(nums));
any help or thoughts as to what i may be not be realizing or doing ?
The problem is within your for loops. More specifically, you need to declare the variable i before using it. If you alter your code like the below snippet, then your code works just as expected:
let nums = [2, 1, 3, 4, 5, 6];
function sortArray(nums) {
let arr = new Array();
let smallest_index;
for (let i = 0; i < nums.length; i++) {
smallest_index = find_smallest(nums);
arr.push("5");
}
return arr;
}
function find_smallest(arr) {
let smallest = arr[0];
let smallest_index = 0;
for (let i = 1; i < arr.length; i++) {
if (arr[i] < smallest) {
console.log("this");
smallest = arr[i];
smallest_index = i;
}
}
return smallest_index;
}
console.log(sortArray(nums));
The only difference is using
for (let i = 1; ...
instead of
for (i = 1; ...

Adding up in JavaScript

I'm learning basics of JavaScript as I'm more of a back-end guy.
I've got this bit of code that is returning NULL but don't
know why:
function sum(...args) {
let added = 0;
for (var x = 0; x <= args.length; x++) {
added += args[x];
}
return added;
}
console.log(sum(1, 2, 3)); // 6
The issue is that you loop goes up to the length of the array, so at the last iteration, it will try getting the value of args[length], which is undefined (array indices go from 0 to length - 1). This explains why the function returns NaN.
To fix this, simply make your function loop till length - 1, and not length.
function sum(...args) {
let added = 0;
for (var x = 0; x < args.length; x++) {
added += args[x];
}
return added;
}
console.log(sum(1, 2, 3)); // 6
Use the below code, I think its internally getting an array index out of bound exception
function sum(...args) {
let added = 0;
for (var x = 0; x < args.length; x++) {
added += args[x];
}
return added;
}
console.log(sum(1, 2, 3));

Write a function which returns the sum of the values for each parameter it receives

I want the result to be the sum of every number, but instead, it only sums the first number with the rest. For example if the parameter were : 1,2,3,4,5
it should come out with 15 but instead, it became 3456. Where did i go wrong?
Thank u guys, i m new to this and thing were really complicated :((
function func1(sum) {
var result = '';
var i;
for (i = 1; i < arguments.length; i++) {
result += arguments[i] + sum;
}
return result;
}
Start with result being a number, not a string: var result = 0.
If you're iterating through arguments, you may as well skip the named first argument altogether.
Start iterating from 0, not 1.
function func1() {
var result = 0;
var i;
for (i = 0; i < arguments.length; i++) {
result += arguments[i];
}
return result;
}
console.log(func1(1, 2, 3, 4, 5));
This should work
function sum(value) {
let result = 0;
for(let i =0; i < value.length; i++) {
result +=value[i];
}
return result
}
let arry = [1,2,3,4,5]
console.log(sum(arry)) //15

what is the wrong with this javascript function?

I want to know what is wrong with this function that takes array and summation it's elements
var arr = [1,2,3,4,5,6,7,8,9,10];
var sum = 0;
var arraySum = function () {
for (var i = 0 ; i<= arr.length ; i++) {
sum += arr[i];
}
console.log(sum);
};
arraySum(arr);
You are trying to access an element outside of the array, this returns undefined.
for (var i = 0 ; i<= arr.length ; i++) {
// ^ the equal sign
replace it with
for (var i = 0 ; i< arr.length ; i++) {
var arr = [1,2,3,4,5,6,7,8,9,10];
var sum = 0;
var arraySum = function () {
for (var i = 0; i< arr.length; i++) {
sum += arr[i];
}
};
arraySum(arr);
document.write(sum);
The problem is there with your for loop's condition. Use < when you are checking against the length,
for (var i = 0 ; i < arr.length ; i++) {
//------------------^ replaced the <= with <
Your loop will iterate additionally one time, at that time the value will be undefined.
So sum + undefined = NaN.
If you want to use <= for sure then subtract 1 from the length and use it.
for (var i = 0 ; i <= arr.length-1 ; i++) {
//------------------------------^ decrement the length by 1
Or you can do the entire process with Array.prototype.reduce
var arr = [1,2,3,4,5,6,7,8,9,10];
var sum = arr.reduce((a, b) => { return a + b }, 0);
Also you can use Array.prototype.forEach function
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var sum = 0;
arr.forEach(function(element) {
sum += element;
});
console.log(sum);

Categories

Resources