0

I’m trying to get the set of numbers from a function (not included here) to be sorted in ascending order. But the sort function won’t work anywhere. What am I doing wrong?

arrayX = [];

array.sort((x,y) => x-y);
5
  • function params are c and y, and you are using x and y Commented Jul 25, 2022 at 0:48
  • Oh no that’s a mistake. On my system it’s x,y. That’s a typing mistake from my phone Commented Jul 25, 2022 at 0:50
  • not included here ... the function probably doesn't do what you think it does, hence you're probably sorting an empty array Commented Jul 25, 2022 at 1:08
  • You must assign to a new variable to store the result Commented Jul 25, 2022 at 2:39
  • Oh no it’s generating an array. But anyway I’ve solved it thanks Commented Jul 25, 2022 at 23:18

1 Answer 1

1

I think the issue is that you are not setting the arrayX array equal to the sorted array.

I tried this and it worked for me.

let arr = [51, 12, 34, 63, 26, 84, 13];
let newArr = [];

newArr = arr.sort((a, b) => a - b);

console.log(newArr);

I made up the arr array to represent a bunch of random numbers for the test assuming the array you have also contains numbers, this should work.

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

3 Comments

Do you understand that arr.sort is an in-place sort? while of course you can assign the result to a new array, in this code arr is actually sorted - since it's the same object as newArr, and the =[] in let newArr = [] is redundant
Absolutely! I assumed the reason they included arrayX and set it to an empty array was for this purpose. You are absolutely correct. My intentions were to format it the way the given code was.
all good - I think arrayX in the question was actually the one and only array - but that's my interpretation of a very vague question :p

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.