Home > Net >  Can the sort function work for an array with arbitrary numbers in JavaScript?
Can the sort function work for an array with arbitrary numbers in JavaScript?

Time:07-26

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);

CodePudding user response:

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.

  • Related