# Where is my logic wrong with sort(), Math.min/max within Sum All Numbers in a Range

Tell us what’s happening:

I think I have a few things right, but I’m not too sure about the details.

I’ve put in comments below on my code. I’d appreciate a bit of nudge/guidance in the correct direction, especially correction of my improper logic.

``````
function sumAll(arr) {
//organizing arr into consecutive order
var sumOne = arr.sort((a,b)=>{
return a-b;
});
//finding minimum, maximum number of this organized array
var minNum = Math.min(sumOne);
var maxNum = Math.max(sumOne);

var result;
//run for loop to iterate through consecutive list and compel elements to add one another
for(i=0; minNum <= maxNum; i++){
//as long as I remains lower than maximum it adds together the two current consecutive number pairs.
if(i <= maxNum){
result = i + i+1;
}
}
return result;
}
console.log(result);
sumAll([1, 4]);
``````

Where am I wrong?

User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134`.

You seem to be establishing which is the smaller number twice. Sorting would work and using Math.max / Math.min would work also but I’m not sure you need both.

Your for loop as written will never reach an end condition so you have an infinite loop.

You are on the right track with the for loop but you might need to review for loops some before continuing. The most basic for loop simply generates numbers from an initial number to and ending number (by ones if you increment by i++). In the test case below you want to generate all the numbers from 1 to 4 so you can sum them.

for example…

``````for(let i = 5; i <=10; i++){
console.log(i);
}
``````

5 then 6 then 7 then 8 then 9 then 10

``````function sumAll(arr) {
//organizing arr into consecutive order
var sumOne = arr.sort((a,b)=>{
return a-b;
});

// ONCE YOU HAVE SORTED YOU ALREADY KNOW THE FIRST ELEMENT IS THE SMALLER NUMBER
var minNum = Math.min(sumOne);
var maxNum = Math.max(sumOne);

var result;

//minNum will always be <= maxNum so this loop will never end
for(i=0; minNum <= maxNum; i++){
//as long as I remains lower than maximum it adds together the two current consecutive number pairs.
if(i <= maxNum){
result = i + i+1;  // CAN YOU EXPLAIN HOW THIS WORKS?
}
}
return result;
}
console.log(result);
sumAll([1, 4]);
``````
`````` var sumOne = arr.sort((a,b)=>{
return a-b;
});
//finding minimum, maximum number of this organized array
var minNum = Math.min(sumOne);
var maxNum = Math.max(sumOne);
``````

You have redundancy here. You can achieve your goal by either sorting the array or using `Math.min()` and `Math.max()`. There is no need for both.

``````for(i=0; minNum <= maxNum; i++)
``````
• Why are you starting iterating at 0 instead of `minNum`?
• Since you aren’t modifying `minNum` (and you shouldn’t), `minNum <= maxNum` will always be true and the loop will run forever.
``````result = i + i+1;
``````

Why are you adding both `i` and `i+1`?

In addition to above, there’s an issue with these lines:

``````var minNum = Math.min(sumOne);
var maxNum = Math.max(sumOne);
``````

Math min/max don’t take arrays, they take arguments (like `Math.min(1,2)` not `Math.min([1,2])`. To put a list of values in, you need to spread the array into individual values, ie `Math.min(...arr)` (or use the apply method, which allows you to execute a function with the arguments given as an array, ie `Math.min.apply(null, arr)`)

1 Like

My code is below and I have a few questions in terms of what may lead me to a correct solution:

1.I am not clear on what the spread operator is doing to allow me to perform a Math function on it, but simply following the lead of a past commenter and wondered if someone would explain this to me.
2. The function I have ordered to complete after iterating through using the for loop seems as if it should have an if statement, but I’m not sure what parameters are necessary for an if statement in this case. Is it necessary?
3.Is sort() a necessity in a problem like this? Or, does it just make solving a problem of this particular type easier? And does it REALLY make it easier or is that just a faulty perception?

``` function sumAll(arr) { //order array consecutively let ordAll = arr.sort((a,b)=>{ return a-b; }); //establish minNum as containing smallest element in array var minNum = Math.min(…ordAll); //iterate through for loop using ordAll as consecutive array for(i=minNum; i < ordAll.length; i++){ //use ordAll to add all numbers in order ordAll = ordAll[i] + ordAll[i]; } return ordAll; } sumAll([10, 4]);```

What the spread operator does is go through an iterable thing (in this case an array, but it works for strings, Maps and Sets as well), and yields those values one by one. So it’s taking that array (something like `[10, 0]`), and when it gets put into `Math.min`, which takes a series of arguments, it does something sorta like:

``````// spreading this array [10, 0]
Math.min(...[10, 0])
// yields the first value, not done yet
Math.min(10, ...)
// yields the second value, not done yet
Math.min(10, 0)
// all done!, can now execute Math.min
0
``````

You can see what it’s doing under the hood in the console if you do something like this (the setup may look a bit alien):

``````// using this array, but change the values in the array to play around, and try with a string
const myIterable = [1, 2, 3, 4, 5]
// this is the step that will look wierd:
const myIterableIterator = myIterable[Symbol.iterator]()

// now I can yield values:
myIterableIterator.next()
// returns { value: 1, done: false }
myIterableIterator.next()
// returns { value: 2, done: false }
myIterableIterator.next()
// returns { value: 3, done: false }
myIterableIterator.next()
// returns { value: 4, done: false }
myIterableIterator.next()
// returns { value: 5, done: false }
myIterableIterator.next()
// returns { value: undefined, done: true }
// we finished
``````

Is sort() a necessity in a problem like this? Or, does it just make solving a problem of this particular type easier? And does it REALLY make it easier or is that just a faulty perception?

It is not necessary, as you can use min and max. It can make it easier, for example, if you want brevity:

``````const [min, max] = arr.sort((a, b) => a - b);
``````

I still, after years of doing JS, cannot just automatically read `arr.sort((a, b) => a - b)` as “sort this array in ascending order”, I still have to pause and parse what it’s doing, so personally I would always prefer `Math.min` and `Math.max` as it’s obvious what they are doing. Personally I generally avoid using sort unless necessary, mainly out of habit and the [sometimes faulty assumption] that there are better, faster ways to deal with data. There’s nothing wrong with it here though, and if it’s clearer for you and you want to use it, go for it (but as stated, just use sort or min/max, not both), it’s personal preference for me.

I’m logging 10, but I’m not passing the tests. So I’m missing a crucial detail here. I don’t know what I’m missing or if I have too much and that is causing something significant to inhibited. Please help.

``` function sumAll(arr) { var newArr = Math.min(…arr); var newNewArr = Math.max(…arr); var sumSome = newArr + newNewArr; for(var i=0; i < arr.length; i++){ sumSome += arr[i]++; console.log(sumSome) } } sumAll([1, 4]);```

Firstly, try to use sensible names:

``````function sumAll(arr) {
// Don't call it newArr, it is not an array, it is the
// smallest of two numbers
var min = Math.min(…arr);
// Don't call it newNewArr, it is not an array, it
// is the largest of two numbers
var max = Math.max(…arr);
``````

Then why is this here? What is your thinking, why do you think you need to add these numbers together?

``````var sumSome = newArr + newNewArr;
``````

So `arr` is an array of two numbers. It’s always an array of two numbers. This is important, because you’ve decided to loop from 0 to < arr.length, so you loop twice. That’s not going to work. The array that is given to the function is just a container for two numbers. Once you know what the smallest of the two is and what the largest of the two is, it has served it’s purpose: you don’t need it after that.

Then you do a thing with sumSome. And you don’t return anything after the loop is finished (as you’re adding to sumSome, I would expect that to be what you meant to return).

``````for(var i=0; i < arr.length; i++) {
// Again, what is your thinking here?
sumSome += arr[i]++;
console.log(sumSome)
}
}
``````

I’m trying to walk through this in my head, and I can’t even keep track of values here.

You have the min.
You have the max.
Set a variable to 0.
Loop from min to max, adding the value onto that variable each time.
Return that variable.

Got it. Thanks for your help!

1 Like