3

I wish to execute a program with output as :

console.log(range(1, 10));  
// → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  
console.log(range(5, 2, -1));  
// → [5, 4, 3, 2]  
console.log(sum(range(1, 10)));  
// → 55  

I am getting an error for array.length.Please find the code below:

var array = [];

function range (arr){  
    var lower = Math.min(arr[0],arr[1]);    
    var upper = Math.max(arr[0],arr[1]);  

    for (var i=lower;i<=upper;i++){  
        array.push(i);  
    }  
}  

function sum(array){  
    for(var i=0;i < array.length;i++){  
        var total = total+array[i];  
    }  
}  

console.log(sum(range(1, 10)));  

I am at begineers level, please do help. Thanks.

2
  • 2
    dude while calling your range function pass the arguments as range([1,10]) Commented Apr 19, 2016 at 12:22
  • Should the range(5, 2, -1) ==> [-1, 0, 1, 2, 3, 4, 5]?? Commented Apr 19, 2016 at 12:38

12 Answers 12

4

You have a few problems here:

1.) You aren't returning anything in your range function. You need to return the filled array.

2.) You aren't passing the array correctly in the sum function call.

3.) You aren't returning anything in your sum function call.

Without returning any values, you aren't letting your code blocks work with eachother

var array = [];

function range (arr){  
    var lower = Math.min(arr[0],arr[1]);    
    var upper = Math.max(arr[0],arr[1]);  

    for (var i=lower;i<=upper;i++){  
        array.push(i);  
    }
    return array; // return the array to be used in the sum function
}  

function sum(array){  
    var total = 0; // need to create a variable outside the loop scope
    for(var i in array){  
       total = total+array[i];  
    }
    return total;
}  

console.log(sum(range([1,10]))); // pass the array correctly 

Note that you need to set the total variable outside the scope of the for-loop within the sum function. That way you can return the final value. Otherwise, it would return undefined.

See the fiddle: https://jsfiddle.net/udyhb95a/

Sign up to request clarification or add additional context in comments.

Comments

3
  1. You need to pass an array when calling the range function you defined range([1, 10])

  2. You need to rewrite your sum function

As a side note, there are more efficient ways to compute the sum of a range of elements without iterating on them.

function sum_of_range(start, end) {
    return end * (end + 1) / 2 - start * (start + 1) / 2;
}

Edit:

Here is a working sum function

function sum(array) {
    var accumulator = 0;
    for (var i = 0; i < array.length; ++i)
        accumulator += array[i];
    return accumulator;
}

5 Comments

How can I execute second example through this, please can you explain ....console.log(range(5, 2, -1)); // → [5, 4, 3, 2]
The sum_of_range function is missing some parentheses and does not need the last / 2. Should read: function sum_of_range(start, end) { return end * (end + 1) / ((2 - start) * (start + 1)) }
That said, here is how I would write it function sumOfRange(start, end) { let average = (start + end) / 2; let numberOfTerms = (end - start)/ 1 + 1; return average * numberOfTerms; } Good discussion here.
Also probably worth mentioning that even with the adjustments above sum_of_range will only work for sequences starting from 1, whereas sumOfRange does not have that limitation and will correctly tally 3,10 for example.
@rdela Both versions will work and are not limited to ranges starting by 1
2

Here you declare a function with one parameter as an array

function range (arr){ 
      ...

But here you call a function with two arguments as numbers

console.log(range(1, 10)); 

Use this call function

console.log(range([1, 10])); 

And don't use for..in for arrays

for(var i in array){ it doesn't work as you expect 

Use forEach function or plan for loop

Also you have some error in sum function

See working example below:

function range(arr) {
    var array = [];
    var lower = Math.min(arr[0], arr[1]);
    var upper = Math.max(arr[0], arr[1]);

    for (var i = lower; i <= upper; i++) {
        array.push(i);
    }
    return array;
}

function sum(array) {
    var total = 0;
    for (var i  = 0; i < array.length; i++) {
        total = total + array[i];
    }
    return total;
}

document.write('range ' + range([1, 10]) + '<br>');
document.write('sum ' + sum(range([1, 10])));

4 Comments

It was still showing me an undefined result, while I added a "return array" at the end of range function, it is working fine now.Thanks
@gauravsharma yes, you are using array as global variable. You can use that variable as local in the function and return it.
Do you want to say as global var does not need to return,because inspite of keeping it global I was not able to get answer without returning that value.
@gauravsharma 'global var does not need to return' yes, you can use that global variable in other function, I've edited the answer and made the array variable local and now it returns from a function. It's better for your case.
1

You need to modify sum & range function

function range (){
    var array = []; 
    var lower = Math.min.apply(null, arguments);    
    var upper = Math.max.apply(null, arguments);    

    for (var i=lower;i<=upper;i++){  
        array.push(i);  
    }
    return array;  
} 

function sum(array){  
    return  array.reduce((x,y)=>x+y,0);
} 

console.log(range(1, 10)); 
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(range(5, 2, -1)); //if we are considering min & max from params
// [-1, 0, 1, 2, 3, 4, 5]
console.log(sum(range(1, 10)));
// 55

3 Comments

The use of reduce is elagant, I would do it the same way. But for a newbie this might not be the simplest function to comprehend
Yea, but they will get glimpse of future ..;)
cool, this is good answer, it shows the use of javascript arrays(reduce method).Thanks...:)
0

Hello Dear check it now.

                var array = [];

                function range(arr, arr1) {
                    var lower = Math.min(arr);
                    var upper = Math.max(arr1);
                    for (var i = lower; i <= upper; i++) {
                        array.push(i);
                    }
                }

                function sum() {
                    var total = 0;
                    for (var i = 0; i < array.length; i++) {
                        total = total + array[i];
                    }
                    return total;
                }
                console.log(sum(range(1, 10)));

Comments

0

This is the correct answer to the problem at the end of the data structures chapter within Eloquent JavaScript

function range(start, end, step) {
  let arr = []; //declare an empty array
  var step = step || 1;//tests to see if step was supplied, otherwise it's 1
  if(start < end) 
  {
    for(let i = start; i <= end; i += step)
    {
      arr.push(i);
    }
  }
  else 
  {
    for(let i = start; i >= end; i += step)
    {
      arr.push(i);
    }
  }
  return arr;
}
function sum(array) {
  let total = 0;
  for(let i = 0; i < array.length; i++) 
  { 
    total += array[i];
  }
  return total;
}

console.log(range(1, 10));
// → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(range(5, 2, -1));
// → [5, 4, 3, 2]
console.log(sum(range(1,10)));
// → 55

Comments

0

This solution takes into account of entering a step that isn't expected to be positive/negative, i.e range from 1 to 5, we would expect step to be positive, but if the user somehow entered a negative step then an empty array would occur.

The browser actually hangs for the opposite, if the array is expected to decrease, but the step sizes are > 0.

'use strict';

function range(start, end, step = 1){
    let output = [];

    if (start > end){
        // Sanity check, all steps if expected to go down should be negative
        if (step > 0){
            step = -step;
        }

        for (;start >= end; start += step){
            console.log(start);
            output.push(start);
        }
    }
    else{
        // Likewise, as all steps should be positive
        if (step < 0){
            step = -step;
        }

        for (;start <= end; start += step){
            output.push(start);
        }
    }
    return output;
}

function sum(arr){
    let output = 0;
    for (let i of arr){
        output += i;
    }
    return output;
}

console.log(range(1, 5, 1));
// → [1, 2, 3, 4, 5]

console.log(range(5, 1, -1));
// → [5, 4, 3, 2, 1]

// Notice this one step is a positive, but this is handled (original solution returned empty array)
console.log(range(5, 1, 1));
// → [5, 4, 3, 2, 1]

console.log(sum(range(1,10)));
// → 55

An improvement onto this is to use the reduce function for an array to sum instead of a for loop, i.e:

function sum(array){  
    return array.reduce((x,y)=>x+y,0);
} 

Comments

0

For people finding this later on as I did, here is a way to write the range function so you can pass the input as written in the original question:

console.log(sum(range(1, 10)));

…and a cleaned up sum function similar to the one in A. Sharma's answer:

function range(lower, upper) {
  let array = []
  for (let i = lower; i <= upper; i++) {
    array.push(i);
  }
  return array;
}

function sum(array) {
  let total = 0;
  for (let i in array) {
    total = total + array[i];
  }
  return total;
}

console.log(sum(range(1, 10)));

Also worth mentioning:

Comments

0

This is the best solution I've got

function range(x,y){
    var arr = [];
    for(x;x<=y;x++){
        arr.push(x);
    };
    return arr;
};

function sum(array){
    return array.reduce((a,b) => a + b, 0);
};

console.log(sum(range(1,10)));

Comments

0

This answer is quite late but I am learning these things now and want to share my solution. I have not seen this solution provided for the specific question "Sum of a range in Javascript" so I wanted to share it. What I have done here is made use of the pop method for the array which allowed me not to specifically pass an array argument to the range function but to provide a solution to the argument in the way it was originally presented in the question.

var result = [];
var counter = 0;
function range(start, end) {
  for (let i = start; i <= end; i++) {
    result.push(i);
  }
  return result;
}

function sum(array) {
    for (let i = 0; i < result.length; i++) {
      counter += result.pop(i);
    }
    return counter;
}

console.log(range(1, 10));
// → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(sum(range(1, 10)));
// → 55

Comments

0

This can be accomplished very easily and efficiently without any globally scoped vars.

It's not clear in the original question what behavior should be applied to the -1 argument. It seems to be an indicator to reverse the range. In the below example, I've used a boolean to check this argument. A value of -1 would actually be the same as not providing a third argument. To reverse the range, pass in any truthy value.

function range(from, to, reverse) {
  // Make sure our inputs are actually numbers
  if (Number(from) != from || Number(to) != to) {
    throw new TypeError("range() expects a Number as both it's first and second argument");
  }

  let o = []; // initialize our output array
  
  // get the lowest value argument as our starting index
  let i = Math.min(from, to);
  
  // get the highest value argument as our ending index
  let x = Math.max(from, to); 

  // push i onto our output array and then increment until i == x
  while (i <= x) { o.push(i); i++; }

  // reverse the range order if necessary
  if (reverse) { o = o.reverse(); }
  
  // return our output array
  return o;
}

Then we can use Array.reduce to iterate through the range array and add each value (b) to the one before it (a) with the addition assignment operator (+=).

function sum(range) {
  if (!(range instanceof Array)) {
    throw new TypeError("sum() expects an Array as it's only argument");
  } return range.reduce((a,b) => a+=b);
}

Testing it:

let a = range(1,10);
let b = range(5,2);
let c = range(5,2,true);
let d = range(3,-1);
let e = range(10,10);

console.log(a); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
console.log(b); // [ 2, 3, 4, 5 ]
console.log(c); // [ 5, 4, 3, 2 ]
console.log(d); // [ -1, 0, 1, 2, 3 ]
console.log(e); // [ 10 ]
console.log(range('test', 10)); // TypeError
console.log(range(1, 'test')); // TypeError

console.log(sum(a)); // 55
console.log(sum(b)); // 14
console.log(sum(c)); // 14
console.log(sum(d)); // 5
console.log(sum(e)); // 10
console.log(sum('test')); // TypeError

Comments

0

here my answer, I'd glad if you give me feedback about this solution.

let arr = [];

function range(x, y) {
for (let i = x; i <= y; i++) {
    arr.push(i);
}
return arr;
}

function sum(array) {
const many = array.reduce((total, number) => {
    return total + number;
}, 0);
return many;
}

console.log(sum(range(1, 10)));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.