Intermediate Algorithm Scripting - Sum All Numbers in a Range

Hello

Could u plz tell me why my code does not work. plz note that it is not complete yet, I have written only the ascending order part which does not work.
function sumAll(arr) {
let newArr= […arr];
function order(newArr){
return newArr.sort(function(a,b){
return a===b ? 0: a<b ? -1: 1;
})
}
return newArr;
}

console.log(sumAll([1, 4]));
console.log(sumAll([5, 4]));

console.log([5,4]) still shows [5,4] not [4,5].

Your code so far

function sumAll(arr) {
  let newArr= [...arr];
 function order(newArr){
   return newArr.sort(function(a,b){
   return a===b ? 0: a<b ? -1: 1;
  })
 }
  return newArr;
}

console.log(sumAll([1, 4]));
console.log(sumAll([5, 4]));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36

Challenge: Intermediate Algorithm Scripting - Sum All Numbers in a Range

Link to the challenge:

Hey, is it necessary that you order them? You just have to return the sum of all numbers in the array.
If it’s something you wanna try anyway, although it’s okay to define functions inside functions here your function order is not really necessary. See that you are not using at all the return statement on your function, you could just have that same .sort() applied anywhere.
Nevertheless, to sort in an ascending order using should work:

.sort(function(a, b){return a-b});

These sort of things you can always just look them up at w3schools or developer.mozilla.

Hi,
thank you for your reply. It might not be necessary but as I mentioned, I first started to sort them, my problem is right there, not the whole question, my question is why it does not sort the arrays in ascending order:
here s my code, still does not work:
function sumAll(arr) {
let newArr= […arr];
function order(newArr){
return newArr.sort(function(a,b){
return a-b;
})
}
return newArr;
}

console.log(sumAll([1, 4]));
console.log(sumAll([5,3])); ========> this is showing [5,3] not [3,5]

Adding to what I just mentioned, and according to your answer, I changed the code and it worked:
function sumAll(arr) {
let newArr= […arr];
newArr.sort(function(a,b){
return a-b;
})

return newArr;
}

console.log(sumAll([1, 4]));
console.log(sumAll([5,3])); ======> shows [3,5]
but can you explain why t was not working with another function inside?

If you are talking about this:

function sumAll(arr) {
  let newArr = [...arr];
  function order(newArr) {
    return newArr.sort(function (a, b) {
      return a - b;
    })
  }
  return newArr;
}

It’s because you are never calling the function order in your code. You are just defining it but not doing anything with it. If you want to sort the array with the function order then you need to invoke the function and pass the array into it.

1 Like

Understood,
thank you so much.