0

I'm trying to sort the numbers in each array from greatest to smallest, but only the first one is being sorted. Do I need another nested loop? I'm stuck.

function sortNums(arr) {
  for(var i = 0; i < arr.length; i++){
     arr[i] = arr[i].sort(function(a, b){return b-a;});
     return arr; 
  }
}

sortNums([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

1 Answer 1

1

When using the return keyword the function immediately terminated. Move it outside the iteration and you should be good:

function sortNums(arr) {
  for(var i = 0; i < arr.length; i++) {
     arr[i] = arr[i].sort(function(a, b) {
       return b - a;
     });
  }
  return arr;
}

sortNums([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
Sign up to request clarification or add additional context in comments.

1 Comment

@Austin No problem, sometimes you just stare yourself blind on the problem :-)

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.