EN
JavaScript - array sort() method doesn't work properly
1 answers
3 points
Could you tell me why JavaScript doesn't sort the array of a numbers correctly?
My code:
xxxxxxxxxx
1
const numbers = [20, 1, 100, 3];
2
numbers.sort();
3
4
console.log(numbers); // result: [1, 100, 20, 3]
1 answer
3 points
It's because JavaScript sorts arrays alphabetically.
Check out our article: JavaScript - sort array.
This should solve your problem:
xxxxxxxxxx
1
const numbers = [20, 1, 100, 3];
2
numbers.sort((a, b) => {
3
return a - b;
4
});
5
6
console.log(numbers); // result: [1, 3, 20, 100]
0 commentsShow commentsAdd comment