freeCodeCamp Challenge Guide: Sum All Numbers in a Range

My code was not smart kkkkkkkk

function sumAll(arr) {
var max = arr.reduce(function(a, b) {
return Math.max(a, b);
});
var min = arr.reduce(function(a, b) {
return Math.min(a, b);
});

for(var i=min+1;i<max;i++){
arr.push(i);
}

var total = arr.reduce(function(sum, value) {
return sum + value;
}, 0);

return total;
}

sumAll([1, 4]);

Well I did use reduce(). I’ll call it intermediate:-

    function sumAll(arr) {
  return arr.reduce(function(initial, secondValue){
    var sumOfNumbers = 0;
     for(var i = Math.min(initial, secondValue); i <= Math.max(initial, secondValue); i++ )    {
         sumOfNumbers += i;
     }
    
      return sumOfNumbers;
  });
}

sumAll([1, 4]);

Hope it helps.

My code is getting the correct answer but is not allowing me to submit. I had this issue before, not sure if its my code or the site?

var sum = 0;
 function sumAll(arr) {
   arr.sort(function(a, b) {
   return a - b;
 });
   while (arr[0] <= arr[1]) {
     sum = sum + arr[0];
     arr[0]++;
   }
   return sum;
 }
  • used a for loop with Math.min() as starting point, and Math.max() as end point
  • iterate and pushed into an array
  • applied Array.prototype.reduce()

function sumAll(arr) {
var totalArr = [];

for (var i = Math.min(arr[0],arr[1]); i <= Math.max(arr[0],arr[1]); i++) {
totalArr.push(i);
}

var total = totalArr.reduce(
function (acc,cur) { return acc + cur;});
return total;
}

sumAll([1, 4]);

3 Likes

It is not very short or efficient but here is my solution. Please let me know what you think. Quick question; may be I am blind but why there are no comments from 2019. Is it because there are enough solutions shown on the forum? Thank you.

function sumAll(arr) {
  arr.sort(function(a,b){
    return a-b;
  });
  console.log(arr);
  let i = 1;
  let y = [];
  while(arr[0] + i < arr[arr.length-1]){
   
   y.push(arr[0] + i);
   i++; 
  }
 let z = arr.concat(y);
  return z.reduce((a,b) => a+b);
}

sumAll([10, 5]);
3 Likes